From a2f4cbcbc133f26b47e8664dfa6286f31a297127 Mon Sep 17 00:00:00 2001 From: Seokhyun Lee <7948302+henrylee97@users.noreply.github.com> Date: Fri, 1 Dec 2023 09:42:10 +0900 Subject: [PATCH 1/4] refactor(java): commons-lang N-classes (#142) --- Java/commons-lang-NumberUtils_1116/Dockerfile | 18 + Java/commons-lang-NumberUtils_1116/buggy.java | 1641 ++++++++++++++++ .../metadata.json | 21 + Java/commons-lang-NumberUtils_1116/npe.json | 7 + Java/commons-lang-NumberUtils_223/Dockerfile | 18 + Java/commons-lang-NumberUtils_223/buggy.java | 1654 ++++++++++++++++ .../metadata.json | 21 + Java/commons-lang-NumberUtils_223/npe.json | 7 + Java/commons-lang-NumberUtils_275/Dockerfile | 18 + Java/commons-lang-NumberUtils_275/buggy.java | 1654 ++++++++++++++++ .../metadata.json | 21 + Java/commons-lang-NumberUtils_275/npe.json | 7 + Java/commons-lang-NumberUtils_452/Dockerfile | 18 + Java/commons-lang-NumberUtils_452/buggy.java | 1710 +++++++++++++++++ .../metadata.json | 21 + Java/commons-lang-NumberUtils_452/npe.json | 7 + Java/commons-lang-NumberUtils_657/Dockerfile | 18 + Java/commons-lang-NumberUtils_657/buggy.java | 1642 ++++++++++++++++ .../metadata.json | 21 + Java/commons-lang-NumberUtils_657/npe.json | 7 + Java/commons-lang-NumberUtils_679/Dockerfile | 18 + Java/commons-lang-NumberUtils_679/buggy.java | 1645 ++++++++++++++++ .../metadata.json | 21 + Java/commons-lang-NumberUtils_679/npe.json | 7 + Java/commons-lang-NumberUtils_695/Dockerfile | 18 + Java/commons-lang-NumberUtils_695/buggy.java | 1644 ++++++++++++++++ .../metadata.json | 21 + Java/commons-lang-NumberUtils_695/npe.json | 7 + Java/commons-lang-NumberUtils_713/Dockerfile | 18 + Java/commons-lang-NumberUtils_713/buggy.java | 1646 ++++++++++++++++ .../metadata.json | 21 + Java/commons-lang-NumberUtils_713/npe.json | 7 + Java/commons-lang-NumberUtils_732/Dockerfile | 18 + Java/commons-lang-NumberUtils_732/buggy.java | 1646 ++++++++++++++++ .../metadata.json | 21 + Java/commons-lang-NumberUtils_732/npe.json | 7 + Java/commons-lang-NumberUtils_749/Dockerfile | 18 + Java/commons-lang-NumberUtils_749/buggy.java | 1651 ++++++++++++++++ .../metadata.json | 21 + Java/commons-lang-NumberUtils_749/npe.json | 7 + Java/commons-lang-NumberUtils_784/Dockerfile | 18 + Java/commons-lang-NumberUtils_784/buggy.java | 1644 ++++++++++++++++ .../metadata.json | 21 + Java/commons-lang-NumberUtils_784/npe.json | 7 + 44 files changed, 18683 insertions(+) create mode 100644 Java/commons-lang-NumberUtils_1116/Dockerfile create mode 100644 Java/commons-lang-NumberUtils_1116/buggy.java create mode 100644 Java/commons-lang-NumberUtils_1116/metadata.json create mode 100644 Java/commons-lang-NumberUtils_1116/npe.json create mode 100644 Java/commons-lang-NumberUtils_223/Dockerfile create mode 100644 Java/commons-lang-NumberUtils_223/buggy.java create mode 100644 Java/commons-lang-NumberUtils_223/metadata.json create mode 100644 Java/commons-lang-NumberUtils_223/npe.json create mode 100644 Java/commons-lang-NumberUtils_275/Dockerfile create mode 100644 Java/commons-lang-NumberUtils_275/buggy.java create mode 100644 Java/commons-lang-NumberUtils_275/metadata.json create mode 100644 Java/commons-lang-NumberUtils_275/npe.json create mode 100644 Java/commons-lang-NumberUtils_452/Dockerfile create mode 100644 Java/commons-lang-NumberUtils_452/buggy.java create mode 100644 Java/commons-lang-NumberUtils_452/metadata.json create mode 100644 Java/commons-lang-NumberUtils_452/npe.json create mode 100644 Java/commons-lang-NumberUtils_657/Dockerfile create mode 100644 Java/commons-lang-NumberUtils_657/buggy.java create mode 100644 Java/commons-lang-NumberUtils_657/metadata.json create mode 100644 Java/commons-lang-NumberUtils_657/npe.json create mode 100644 Java/commons-lang-NumberUtils_679/Dockerfile create mode 100644 Java/commons-lang-NumberUtils_679/buggy.java create mode 100644 Java/commons-lang-NumberUtils_679/metadata.json create mode 100644 Java/commons-lang-NumberUtils_679/npe.json create mode 100644 Java/commons-lang-NumberUtils_695/Dockerfile create mode 100644 Java/commons-lang-NumberUtils_695/buggy.java create mode 100644 Java/commons-lang-NumberUtils_695/metadata.json create mode 100644 Java/commons-lang-NumberUtils_695/npe.json create mode 100644 Java/commons-lang-NumberUtils_713/Dockerfile create mode 100644 Java/commons-lang-NumberUtils_713/buggy.java create mode 100644 Java/commons-lang-NumberUtils_713/metadata.json create mode 100644 Java/commons-lang-NumberUtils_713/npe.json create mode 100644 Java/commons-lang-NumberUtils_732/Dockerfile create mode 100644 Java/commons-lang-NumberUtils_732/buggy.java create mode 100644 Java/commons-lang-NumberUtils_732/metadata.json create mode 100644 Java/commons-lang-NumberUtils_732/npe.json create mode 100644 Java/commons-lang-NumberUtils_749/Dockerfile create mode 100644 Java/commons-lang-NumberUtils_749/buggy.java create mode 100644 Java/commons-lang-NumberUtils_749/metadata.json create mode 100644 Java/commons-lang-NumberUtils_749/npe.json create mode 100644 Java/commons-lang-NumberUtils_784/Dockerfile create mode 100644 Java/commons-lang-NumberUtils_784/buggy.java create mode 100644 Java/commons-lang-NumberUtils_784/metadata.json create mode 100644 Java/commons-lang-NumberUtils_784/npe.json diff --git a/Java/commons-lang-NumberUtils_1116/Dockerfile b/Java/commons-lang-NumberUtils_1116/Dockerfile new file mode 100644 index 000000000..7b7fbe349 --- /dev/null +++ b/Java/commons-lang-NumberUtils_1116/Dockerfile @@ -0,0 +1,18 @@ +FROM ghcr.io/kupl/starlab-benchmarks/java-base:commons-lang + +ENV TZ=Asia/Seoul + +COPY ./metadata.json . +COPY ./npe.json . +COPY ./buggy.java /tmp/buggy.java +RUN export BUGGY_PATH=$(cat metadata.json | jq -r ".npe.filepath") \ + && export BUGGY_LINE=$(cat metadata.json | jq -r ".npe.line") \ + && export BUGGY_MTHD=$(cat metadata.json | jq -r ".npe.npe_method") \ + && mv /tmp/buggy.java $BUGGY_PATH \ + && echo "[{\"filepath\": \"$BUGGY_PATH\", \"line\": $BUGGY_LINE, \"method_name\": \"$BUGGY_MTHD\"}]" | jq . > traces.json + +RUN git init . && git add -A + +RUN $(cat metadata.json | jq -r ".buildCommand") + +RUN $(cat metadata.json | jq -r ".testCommand"); if [ $? -eq 0 ]; then exit 1; fi diff --git a/Java/commons-lang-NumberUtils_1116/buggy.java b/Java/commons-lang-NumberUtils_1116/buggy.java new file mode 100644 index 000000000..48d354a66 --- /dev/null +++ b/Java/commons-lang-NumberUtils_1116/buggy.java @@ -0,0 +1,1641 @@ +/* + * 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 java.lang.reflect.Array; +import java.math.BigDecimal; +import java.math.BigInteger; + +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.SystemUtils; +import org.apache.commons.lang3.Validate; + +/** + *

Provides extra functionality for Java Number classes.

+ * + * @since 2.0 + */ +public class NumberUtils { + + /** Reusable Long constant for zero. */ + public static final Long LONG_ZERO = Long.valueOf(0L); + /** Reusable Long constant for one. */ + public static final Long LONG_ONE = Long.valueOf(1L); + /** Reusable Long constant for minus one. */ + public static final Long LONG_MINUS_ONE = Long.valueOf(-1L); + /** Reusable Integer constant for zero. */ + public static final Integer INTEGER_ZERO = Integer.valueOf(0); + /** Reusable Integer constant for one. */ + public static final Integer INTEGER_ONE = Integer.valueOf(1); + /** Reusable Integer constant for minus one. */ + public static final Integer INTEGER_MINUS_ONE = Integer.valueOf(-1); + /** Reusable Short constant for zero. */ + public static final Short SHORT_ZERO = Short.valueOf((short) 0); + /** Reusable Short constant for one. */ + public static final Short SHORT_ONE = Short.valueOf((short) 1); + /** Reusable Short constant for minus one. */ + public static final Short SHORT_MINUS_ONE = Short.valueOf((short) -1); + /** Reusable Byte constant for zero. */ + public static final Byte BYTE_ZERO = Byte.valueOf((byte) 0); + /** Reusable Byte constant for one. */ + public static final Byte BYTE_ONE = Byte.valueOf((byte) 1); + /** Reusable Byte constant for minus one. */ + public static final Byte BYTE_MINUS_ONE = Byte.valueOf((byte) -1); + /** Reusable Double constant for zero. */ + public static final Double DOUBLE_ZERO = Double.valueOf(0.0d); + /** Reusable Double constant for one. */ + public static final Double DOUBLE_ONE = Double.valueOf(1.0d); + /** Reusable Double constant for minus one. */ + public static final Double DOUBLE_MINUS_ONE = Double.valueOf(-1.0d); + /** Reusable Float constant for zero. */ + public static final Float FLOAT_ZERO = Float.valueOf(0.0f); + /** Reusable Float constant for one. */ + public static final Float FLOAT_ONE = Float.valueOf(1.0f); + /** Reusable Float constant for minus one. */ + public static final Float FLOAT_MINUS_ONE = Float.valueOf(-1.0f); + + /** + *

NumberUtils instances should NOT be constructed in standard programming. + * Instead, the class should be used as NumberUtils.toInt("6");.

+ * + *

This constructor is public to permit tools that require a JavaBean instance + * to operate.

+ */ + public NumberUtils() { + super(); + } + + //----------------------------------------------------------------------- + /** + *

Convert a String to an int, returning + * zero if the conversion fails.

+ * + *

If the string is null, zero is returned.

+ * + *
+     *   NumberUtils.toInt(null) = 0
+     *   NumberUtils.toInt("")   = 0
+     *   NumberUtils.toInt("1")  = 1
+     * 
+ * + * @param str the string to convert, may be null + * @return the int represented by the string, or zero if + * conversion fails + * @since 2.1 + */ + public static int toInt(final String str) { + return toInt(str, 0); + } + + /** + *

Convert a String to an int, returning a + * default value if the conversion fails.

+ * + *

If the string is null, the default value is returned.

+ * + *
+     *   NumberUtils.toInt(null, 1) = 1
+     *   NumberUtils.toInt("", 1)   = 1
+     *   NumberUtils.toInt("1", 0)  = 1
+     * 
+ * + * @param str the string to convert, may be null + * @param defaultValue the default value + * @return the int represented by the string, or the default if conversion fails + * @since 2.1 + */ + public static int toInt(final String str, final int defaultValue) { + if(str == null) { + return defaultValue; + } + try { + return Integer.parseInt(str); + } catch (final NumberFormatException nfe) { + return defaultValue; + } + } + + /** + *

Convert a String to a long, returning + * zero if the conversion fails.

+ * + *

If the string is null, zero is returned.

+ * + *
+     *   NumberUtils.toLong(null) = 0L
+     *   NumberUtils.toLong("")   = 0L
+     *   NumberUtils.toLong("1")  = 1L
+     * 
+ * + * @param str the string to convert, may be null + * @return the long represented by the string, or 0 if + * conversion fails + * @since 2.1 + */ + public static long toLong(final String str) { + return toLong(str, 0L); + } + + /** + *

Convert a String to a long, returning a + * default value if the conversion fails.

+ * + *

If the string is null, the default value is returned.

+ * + *
+     *   NumberUtils.toLong(null, 1L) = 1L
+     *   NumberUtils.toLong("", 1L)   = 1L
+     *   NumberUtils.toLong("1", 0L)  = 1L
+     * 
+ * + * @param str the string to convert, may be null + * @param defaultValue the default value + * @return the long represented by the string, or the default if conversion fails + * @since 2.1 + */ + public static long toLong(final String str, final long defaultValue) { + if (str == null) { + return defaultValue; + } + try { + return Long.parseLong(str); + } catch (final NumberFormatException nfe) { + return defaultValue; + } + } + + /** + *

Convert a String to a float, returning + * 0.0f if the conversion fails.

+ * + *

If the string str is null, + * 0.0f is returned.

+ * + *
+     *   NumberUtils.toFloat(null)   = 0.0f
+     *   NumberUtils.toFloat("")     = 0.0f
+     *   NumberUtils.toFloat("1.5")  = 1.5f
+     * 
+ * + * @param str the string to convert, may be null + * @return the float represented by the string, or 0.0f + * if conversion fails + * @since 2.1 + */ + public static float toFloat(final String str) { + return toFloat(str, 0.0f); + } + + /** + *

Convert a String to a float, returning a + * default value if the conversion fails.

+ * + *

If the string str is null, the default + * value is returned.

+ * + *
+     *   NumberUtils.toFloat(null, 1.1f)   = 1.0f
+     *   NumberUtils.toFloat("", 1.1f)     = 1.1f
+     *   NumberUtils.toFloat("1.5", 0.0f)  = 1.5f
+     * 
+ * + * @param str the string to convert, may be null + * @param defaultValue the default value + * @return the float represented by the string, or defaultValue + * if conversion fails + * @since 2.1 + */ + public static float toFloat(final String str, final float defaultValue) { + if (str == null) { + return defaultValue; + } + try { + return Float.parseFloat(str); + } catch (final NumberFormatException nfe) { + return defaultValue; + } + } + + /** + *

Convert a String to a double, returning + * 0.0d if the conversion fails.

+ * + *

If the string str is null, + * 0.0d is returned.

+ * + *
+     *   NumberUtils.toDouble(null)   = 0.0d
+     *   NumberUtils.toDouble("")     = 0.0d
+     *   NumberUtils.toDouble("1.5")  = 1.5d
+     * 
+ * + * @param str the string to convert, may be null + * @return the double represented by the string, or 0.0d + * if conversion fails + * @since 2.1 + */ + public static double toDouble(final String str) { + return toDouble(str, 0.0d); + } + + /** + *

Convert a String to a double, returning a + * default value if the conversion fails.

+ * + *

If the string str is null, the default + * value is returned.

+ * + *
+     *   NumberUtils.toDouble(null, 1.1d)   = 1.1d
+     *   NumberUtils.toDouble("", 1.1d)     = 1.1d
+     *   NumberUtils.toDouble("1.5", 0.0d)  = 1.5d
+     * 
+ * + * @param str the string to convert, may be null + * @param defaultValue the default value + * @return the double represented by the string, or defaultValue + * if conversion fails + * @since 2.1 + */ + public static double toDouble(final String str, final double defaultValue) { + if (str == null) { + return defaultValue; + } + try { + return Double.parseDouble(str); + } catch (final NumberFormatException nfe) { + return defaultValue; + } + } + + //----------------------------------------------------------------------- + /** + *

Convert a String to a byte, returning + * zero if the conversion fails.

+ * + *

If the string is null, zero is returned.

+ * + *
+     *   NumberUtils.toByte(null) = 0
+     *   NumberUtils.toByte("")   = 0
+     *   NumberUtils.toByte("1")  = 1
+     * 
+ * + * @param str the string to convert, may be null + * @return the byte represented by the string, or zero if + * conversion fails + * @since 2.5 + */ + public static byte toByte(final String str) { + return toByte(str, (byte) 0); + } + + /** + *

Convert a String to a byte, returning a + * default value if the conversion fails.

+ * + *

If the string is null, the default value is returned.

+ * + *
+     *   NumberUtils.toByte(null, 1) = 1
+     *   NumberUtils.toByte("", 1)   = 1
+     *   NumberUtils.toByte("1", 0)  = 1
+     * 
+ * + * @param str the string to convert, may be null + * @param defaultValue the default value + * @return the byte represented by the string, or the default if conversion fails + * @since 2.5 + */ + public static byte toByte(final String str, final byte defaultValue) { + if(str == null) { + return defaultValue; + } + try { + return Byte.parseByte(str); + } catch (final NumberFormatException nfe) { + return defaultValue; + } + } + + /** + *

Convert a String to a short, returning + * zero if the conversion fails.

+ * + *

If the string is null, zero is returned.

+ * + *
+     *   NumberUtils.toShort(null) = 0
+     *   NumberUtils.toShort("")   = 0
+     *   NumberUtils.toShort("1")  = 1
+     * 
+ * + * @param str the string to convert, may be null + * @return the short represented by the string, or zero if + * conversion fails + * @since 2.5 + */ + public static short toShort(final String str) { + return toShort(str, (short) 0); + } + + /** + *

Convert a String to an short, returning a + * default value if the conversion fails.

+ * + *

If the string is null, the default value is returned.

+ * + *
+     *   NumberUtils.toShort(null, 1) = 1
+     *   NumberUtils.toShort("", 1)   = 1
+     *   NumberUtils.toShort("1", 0)  = 1
+     * 
+ * + * @param str the string to convert, may be null + * @param defaultValue the default value + * @return the short represented by the string, or the default if conversion fails + * @since 2.5 + */ + public static short toShort(final String str, final short defaultValue) { + if(str == null) { + return defaultValue; + } + try { + return Short.parseShort(str); + } catch (final NumberFormatException nfe) { + return defaultValue; + } + } + + //----------------------------------------------------------------------- + // must handle Long, Float, Integer, Float, Short, + // BigDecimal, BigInteger and Byte + // useful methods: + // Byte.decode(String) + // Byte.valueOf(String,int radix) + // Byte.valueOf(String) + // Double.valueOf(String) + // Float.valueOf(String) + // Float.valueOf(String) + // Integer.valueOf(String,int radix) + // Integer.valueOf(String) + // Integer.decode(String) + // Integer.getInteger(String) + // Integer.getInteger(String,int val) + // Integer.getInteger(String,Integer val) + // Integer.valueOf(String) + // Double.valueOf(String) + // new Byte(String) + // Long.valueOf(String) + // Long.getLong(String) + // Long.getLong(String,int) + // Long.getLong(String,Integer) + // Long.valueOf(String,int) + // Long.valueOf(String) + // Short.valueOf(String) + // Short.decode(String) + // Short.valueOf(String,int) + // Short.valueOf(String) + // new BigDecimal(String) + // new BigInteger(String) + // new BigInteger(String,int radix) + // Possible inputs: + // 45 45.5 45E7 4.5E7 Hex Oct Binary xxxF xxxD xxxf xxxd + // plus minus everything. Prolly more. A lot are not separable. + + /** + *

Turns a string value into a java.lang.Number.

+ * + *

If the string starts with {@code 0x} or {@code -0x} (lower or upper case) or {@code #} or {@code -#}, it + * will be interpreted as a hexadecimal Integer - or Long, if the number of digits after the + * prefix is more than 8 - or BigInteger if there are more than 16 digits. + *

+ *

Then, the value is examined for a type qualifier on the end, i.e. one of + * 'f','F','d','D','l','L'. If it is found, it starts + * trying to create successively larger types from the type specified + * until one is found that can represent the value.

+ * + *

If a type specifier is not found, it will check for a decimal point + * and then try successively larger types from Integer to + * BigInteger and from Float to + * BigDecimal.

+ * + *

+ * Integral values with a leading {@code 0} will be interpreted as octal; the returned number will + * be Integer, Long or BigDecimal as appropriate. + *

+ * + *

Returns null if the string is null.

+ * + *

This method does not trim the input string, i.e., strings with leading + * or trailing spaces will generate NumberFormatExceptions.

+ * + * @param str String containing a number, may be null + * @return Number created from the string (or null if the input is null) + * @throws NumberFormatException if the value cannot be converted + */ + public static Number createNumber(final String str) throws NumberFormatException { + if (str == null) { + return null; + } + if (StringUtils.isBlank(str)) { + throw new NumberFormatException("A blank string is not a valid number"); + } + // Need to deal with all possible hex prefixes here + final String[] hex_prefixes = {"0x", "0X", "-0x", "-0X", "#", "-#"}; + int pfxLen = 0; + for(final String pfx : hex_prefixes) { + if (str.startsWith(pfx)) { + pfxLen += pfx.length(); + break; + } + } + if (pfxLen > 0) { // we have a hex number + char firstSigDigit = 0; // strip leading zeroes + for(int i = pfxLen; i < str.length(); i++) { + firstSigDigit = str.charAt(i); + if (firstSigDigit == '0') { // count leading zeroes + pfxLen++; + } else { + break; + } + } + final int hexDigits = str.length() - pfxLen; + if (hexDigits > 16 || hexDigits == 16 && firstSigDigit > '7') { // too many for Long + return createBigInteger(str); + } + if (hexDigits > 8 || hexDigits == 8 && firstSigDigit > '7') { // too many for an int + return createLong(str); + } + return createInteger(str); + } + final char lastChar = str.charAt(str.length() - 1); + String mant; + String dec; + String exp; + final int decPos = str.indexOf('.'); + final int expPos = str.indexOf('e') + str.indexOf('E') + 1; // assumes both not present + // if both e and E are present, this is caught by the checks on expPos (which prevent IOOBE) + // and the parsing which will detect if e or E appear in a number due to using the wrong offset + + if (decPos > -1) { // there is a decimal point + if (expPos > -1) { // there is an exponent + if (expPos < decPos || expPos > str.length()) { // prevents double exponent causing IOOBE + throw new NumberFormatException(str + " is not a valid number."); + } + dec = str.substring(decPos + 1, expPos); + } else { + dec = str.substring(decPos + 1); + } + mant = getMantissa(str, decPos); + } else { + if (expPos > -1) { + if (expPos > str.length()) { // prevents double exponent causing IOOBE + throw new NumberFormatException(str + " is not a valid number."); + } + mant = getMantissa(str, expPos); + } else { + mant = getMantissa(str); + } + dec = null; + } + if (!Character.isDigit(lastChar) && lastChar != '.') { + if (expPos > -1 && expPos < str.length() - 1) { + exp = str.substring(expPos + 1, str.length() - 1); + } else { + exp = null; + } + //Requesting a specific type.. + final String numeric = str.substring(0, str.length() - 1); + final boolean allZeros = isAllZeros(mant) && isAllZeros(exp); + switch (lastChar) { + case 'l' : + case 'L' : + if (dec == null + && exp == null + && (numeric.charAt(0) == '-' && isDigits(numeric.substring(1)) || isDigits(numeric))) { + try { + return createLong(numeric); + } catch (final NumberFormatException nfe) { // NOPMD + // Too big for a long + } + return createBigInteger(numeric); + + } + throw new NumberFormatException(str + " is not a valid number."); + case 'f' : + case 'F' : + try { + final Float f = NumberUtils.createFloat(str); + if (!(f.isInfinite() || f.floatValue() == 0.0F && !allZeros)) { + //If it's too big for a float or the float value = 0 and the string + //has non-zeros in it, then float does not have the precision we want + return f; + } + + } catch (final NumberFormatException nfe) { // NOPMD + // ignore the bad number + } + //$FALL-THROUGH$ + case 'd' : + case 'D' : + try { + final Double d = NumberUtils.createDouble(str); + if (!(d.isInfinite() || d.floatValue() == 0.0D && !allZeros)) { + return d; + } + } catch (final NumberFormatException nfe) { // NOPMD + // ignore the bad number + } + try { + return createBigDecimal(numeric); + } catch (final NumberFormatException e) { // NOPMD + // ignore the bad number + } + //$FALL-THROUGH$ + default : + throw new NumberFormatException(str + " is not a valid number."); + + } + } + //User doesn't have a preference on the return type, so let's start + //small and go from there... + if (expPos > -1 && expPos < str.length() - 1) { + exp = str.substring(expPos + 1, str.length()); + } else { + exp = null; + } + if (dec == null && exp == null) { // no decimal point and no exponent + //Must be an Integer, Long, Biginteger + try { + return createInteger(str); + } catch (final NumberFormatException nfe) { // NOPMD + // ignore the bad number + } + try { + return createLong(str); + } catch (final NumberFormatException nfe) { // NOPMD + // ignore the bad number + } + return createBigInteger(str); + } + + //Must be a Float, Double, BigDecimal + final boolean allZeros = isAllZeros(mant) && isAllZeros(exp); + try { + final Float f = createFloat(str); + final Double d = createDouble(str); + if (!f.isInfinite() + && !(f.floatValue() == 0.0F && !allZeros) + && f.toString().equals(d.toString())) { + return f; + } + if (!d.isInfinite() && !(d.doubleValue() == 0.0D && !allZeros)) { + final BigDecimal b = createBigDecimal(str); + if (b.compareTo(BigDecimal.valueOf(d)) == 0) { + return d; + } + return b; + } + } catch (final NumberFormatException nfe) { // NOPMD + // ignore the bad number + } + return createBigDecimal(str); + } + + /** + *

Utility method for {@link #createNumber(java.lang.String)}.

+ * + *

Returns mantissa of the given number.

+ * + * @param str the string representation of the number + * @return mantissa of the given number + */ + private static String getMantissa(final String str) { + return getMantissa(str, str.length()); + } + + /** + *

Utility method for {@link #createNumber(java.lang.String)}.

+ * + *

Returns mantissa of the given number.

+ * + * @param str the string representation of the number + * @param stopPos the position of the exponent or decimal point + * @return mantissa of the given number + */ + private static String getMantissa(final String str, final int stopPos) { + final char firstChar = str.charAt(0); + final boolean hasSign = firstChar == '-' || firstChar == '+'; + + return hasSign ? str.substring(1, stopPos) : str.substring(0, stopPos); + } + + /** + *

Utility method for {@link #createNumber(java.lang.String)}.

+ * + *

Returns true if s is null.

+ * + * @param str the String to check + * @return if it is all zeros or null + */ + private static boolean isAllZeros(final String str) { + if (str == null) { + return true; + } + for (int i = str.length() - 1; i >= 0; i--) { + if (str.charAt(i) != '0') { + return false; + } + } + return str.length() > 0; + } + + //----------------------------------------------------------------------- + /** + *

Convert a String to a Float.

+ * + *

Returns null if the string is null.

+ * + * @param str a String to convert, may be null + * @return converted Float (or null if the input is null) + * @throws NumberFormatException if the value cannot be converted + */ + public static Float createFloat(final String str) { + if (str == null) { + return null; + } + return Float.valueOf(str); + } + + /** + *

Convert a String to a Double.

+ * + *

Returns null if the string is null.

+ * + * @param str a String to convert, may be null + * @return converted Double (or null if the input is null) + * @throws NumberFormatException if the value cannot be converted + */ + public static Double createDouble(final String str) { + if (str == null) { + return null; + } + return Double.valueOf(str); + } + + /** + *

Convert a String to a Integer, handling + * hex (0xhhhh) and octal (0dddd) notations. + * N.B. a leading zero means octal; spaces are not trimmed.

+ * + *

Returns null if the string is null.

+ * + * @param str a String to convert, may be null + * @return converted Integer (or null if the input is null) + * @throws NumberFormatException if the value cannot be converted + */ + public static Integer createInteger(final String str) { + if (str == null) { + return null; + } + // decode() handles 0xAABD and 0777 (hex and octal) as well. + return Integer.decode(str); + } + + /** + *

Convert a String to a Long; + * since 3.1 it handles hex (0Xhhhh) and octal (0ddd) notations. + * N.B. a leading zero means octal; spaces are not trimmed.

+ * + *

Returns null if the string is null.

+ * + * @param str a String to convert, may be null + * @return converted Long (or null if the input is null) + * @throws NumberFormatException if the value cannot be converted + */ + public static Long createLong(final String str) { + if (str == null) { + return null; + } + return Long.decode(str); + } + + /** + *

Convert a String to a BigInteger; + * since 3.2 it handles hex (0x or #) and octal (0) notations.

+ * + *

Returns null if the string is null.

+ * + * @param str a String to convert, may be null + * @return converted BigInteger (or null if the input is null) + * @throws NumberFormatException if the value cannot be converted + */ + public static BigInteger createBigInteger(final String str) { + if (str == null) { + return null; + } + int pos = 0; // offset within string + int radix = 10; + boolean negate = false; // need to negate later? + if (str.startsWith("-")) { + negate = true; + pos = 1; + } + if (str.startsWith("0x", pos) || str.startsWith("0X", pos)) { // hex + radix = 16; + pos += 2; + } else if (str.startsWith("#", pos)) { // alternative hex (allowed by Long/Integer) + radix = 16; + pos ++; + } else if (str.startsWith("0", pos) && str.length() > pos + 1) { // octal; so long as there are additional digits + radix = 8; + pos ++; + } // default is to treat as decimal + + final BigInteger value = new BigInteger(str.substring(pos), radix); + return negate ? value.negate() : value; + } + + /** + *

Convert a String to a BigDecimal.

+ * + *

Returns null if the string is null.

+ * + * @param str a String to convert, may be null + * @return converted BigDecimal (or null if the input is null) + * @throws NumberFormatException if the value cannot be converted + */ + public static BigDecimal createBigDecimal(final String str) { + if (str == null) { + return null; + } + // handle JDK1.3.1 bug where "" throws IndexOutOfBoundsException + if (StringUtils.isBlank(str)) { + throw new NumberFormatException("A blank string is not a valid number"); + } + if (str.trim().startsWith("--")) { + // this is protection for poorness in java.lang.BigDecimal. + // it accepts this as a legal value, but it does not appear + // to be in specification of class. OS X Java parses it to + // a wrong value. + throw new NumberFormatException(str + " is not a valid number."); + } + return new BigDecimal(str); + } + + // Min in array + //-------------------------------------------------------------------- + /** + *

Returns the minimum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the minimum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @since 3.4 Changed signature from min(long[]) to min(long...) + */ + public static long min(final long... array) { + // Validates input + validateArray(array); + + // Finds and returns min + long min = array[0]; + for (int i = 1; i < array.length; i++) { + if (array[i] < min) { + min = array[i]; + } + } + + return min; + } + + /** + *

Returns the minimum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the minimum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @since 3.4 Changed signature from min(int[]) to min(int...) + */ + public static int min(final int... array) { + // Validates input + validateArray(array); + + // Finds and returns min + int min = array[0]; + for (int j = 1; j < array.length; j++) { + if (array[j] < min) { + min = array[j]; + } + } + + return min; + } + + /** + *

Returns the minimum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the minimum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @since 3.4 Changed signature from min(short[]) to min(short...) + */ + public static short min(final short... array) { + // Validates input + validateArray(array); + + // Finds and returns min + short min = array[0]; + for (int i = 1; i < array.length; i++) { + if (array[i] < min) { + min = array[i]; + } + } + + return min; + } + + /** + *

Returns the minimum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the minimum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @since 3.4 Changed signature from min(byte[]) to min(byte...) + */ + public static byte min(final byte... array) { + // Validates input + validateArray(array); + + // Finds and returns min + byte min = array[0]; + for (int i = 1; i < array.length; i++) { + if (array[i] < min) { + min = array[i]; + } + } + + return min; + } + + /** + *

Returns the minimum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the minimum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @see IEEE754rUtils#min(double[]) IEEE754rUtils for a version of this method that handles NaN differently + * @since 3.4 Changed signature from min(double[]) to min(double...) + */ + public static double min(final double... array) { + // Validates input + validateArray(array); + + // Finds and returns min + double min = array[0]; + for (int i = 1; i < array.length; i++) { + if (Double.isNaN(array[i])) { + return Double.NaN; + } + if (array[i] < min) { + min = array[i]; + } + } + + return min; + } + + /** + *

Returns the minimum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the minimum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @see IEEE754rUtils#min(float[]) IEEE754rUtils for a version of this method that handles NaN differently + * @since 3.4 Changed signature from min(float[]) to min(float...) + */ + public static float min(final float... array) { + // Validates input + validateArray(array); + + // Finds and returns min + float min = array[0]; + for (int i = 1; i < array.length; i++) { + if (Float.isNaN(array[i])) { + return Float.NaN; + } + if (array[i] < min) { + min = array[i]; + } + } + + return min; + } + + // Max in array + //-------------------------------------------------------------------- + /** + *

Returns the maximum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the maximum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @since 3.4 Changed signature from max(long[]) to max(long...) + */ + public static long max(final long... array) { + // Validates input + validateArray(array); + + // Finds and returns max + long max = array[0]; + for (int j = 1; j < array.length; j++) { + if (array[j] > max) { + max = array[j]; + } + } + + return max; + } + + /** + *

Returns the maximum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the maximum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @since 3.4 Changed signature from max(int[]) to max(int...) + */ + public static int max(final int... array) { + // Validates input + validateArray(array); + + // Finds and returns max + int max = array[0]; + for (int j = 1; j < array.length; j++) { + if (array[j] > max) { + max = array[j]; + } + } + + return max; + } + + /** + *

Returns the maximum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the maximum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @since 3.4 Changed signature from max(short[]) to max(short...) + */ + public static short max(final short... array) { + // Validates input + validateArray(array); + + // Finds and returns max + short max = array[0]; + for (int i = 1; i < array.length; i++) { + if (array[i] > max) { + max = array[i]; + } + } + + return max; + } + + /** + *

Returns the maximum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the maximum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @since 3.4 Changed signature from max(byte[]) to max(byte...) + */ + public static byte max(final byte... array) { + // Validates input + validateArray(array); + + // Finds and returns max + byte max = array[0]; + for (int i = 1; i < array.length; i++) { + if (array[i] > max) { + max = array[i]; + } + } + + return max; + } + + /** + *

Returns the maximum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the maximum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @see IEEE754rUtils#max(double[]) IEEE754rUtils for a version of this method that handles NaN differently + * @since 3.4 Changed signature from max(double[]) to max(double...) + */ + public static double max(final double... array) { + // Validates input + validateArray(array); + + // Finds and returns max + double max = array[0]; + for (int j = 1; j < array.length; j++) { + if (Double.isNaN(array[j])) { + return Double.NaN; + } + if (array[j] > max) { + max = array[j]; + } + } + + return max; + } + + /** + *

Returns the maximum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the maximum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @see IEEE754rUtils#max(float[]) IEEE754rUtils for a version of this method that handles NaN differently + * @since 3.4 Changed signature from max(float[]) to max(float...) + */ + public static float max(final float... array) { + // Validates input + validateArray(array); + + // Finds and returns max + float max = array[0]; + for (int j = 1; j < array.length; j++) { + if (Float.isNaN(array[j])) { + return Float.NaN; + } + if (array[j] > max) { + max = array[j]; + } + } + + return max; + } + + /** + * Checks if the specified array is neither null nor empty. + * + * @param array the array to check + * @throws IllegalArgumentException if {@code array} is either {@code null} or empty + */ +/** + * Checks if the specified array is neither null nor empty. + * + * @param array + * the array to check + * @throws IllegalArgumentException + * if {@code array} is either {@code null} or empty + */ +private static void validateArray(final java.lang.Object array) { + { + org.apache.commons.lang3.Validate.isTrue(java.lang.reflect.Array.getLength(/* NPEX_NULL_EXP */ + array) != 0, "Array cannot be empty."); + } +} + + // 3 param min + //----------------------------------------------------------------------- + /** + *

Gets the minimum of three long values.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the smallest of the values + */ + public static long min(long a, final long b, final long c) { + if (b < a) { + a = b; + } + if (c < a) { + a = c; + } + return a; + } + + /** + *

Gets the minimum of three int values.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the smallest of the values + */ + public static int min(int a, final int b, final int c) { + if (b < a) { + a = b; + } + if (c < a) { + a = c; + } + return a; + } + + /** + *

Gets the minimum of three short values.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the smallest of the values + */ + public static short min(short a, final short b, final short c) { + if (b < a) { + a = b; + } + if (c < a) { + a = c; + } + return a; + } + + /** + *

Gets the minimum of three byte values.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the smallest of the values + */ + public static byte min(byte a, final byte b, final byte c) { + if (b < a) { + a = b; + } + if (c < a) { + a = c; + } + return a; + } + + /** + *

Gets the minimum of three double values.

+ * + *

If any value is NaN, NaN is + * returned. Infinity is handled.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the smallest of the values + * @see IEEE754rUtils#min(double, double, double) for a version of this method that handles NaN differently + */ + public static double min(final double a, final double b, final double c) { + return Math.min(Math.min(a, b), c); + } + + /** + *

Gets the minimum of three float values.

+ * + *

If any value is NaN, NaN is + * returned. Infinity is handled.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the smallest of the values + * @see IEEE754rUtils#min(float, float, float) for a version of this method that handles NaN differently + */ + public static float min(final float a, final float b, final float c) { + return Math.min(Math.min(a, b), c); + } + + // 3 param max + //----------------------------------------------------------------------- + /** + *

Gets the maximum of three long values.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the largest of the values + */ + public static long max(long a, final long b, final long c) { + if (b > a) { + a = b; + } + if (c > a) { + a = c; + } + return a; + } + + /** + *

Gets the maximum of three int values.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the largest of the values + */ + public static int max(int a, final int b, final int c) { + if (b > a) { + a = b; + } + if (c > a) { + a = c; + } + return a; + } + + /** + *

Gets the maximum of three short values.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the largest of the values + */ + public static short max(short a, final short b, final short c) { + if (b > a) { + a = b; + } + if (c > a) { + a = c; + } + return a; + } + + /** + *

Gets the maximum of three byte values.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the largest of the values + */ + public static byte max(byte a, final byte b, final byte c) { + if (b > a) { + a = b; + } + if (c > a) { + a = c; + } + return a; + } + + /** + *

Gets the maximum of three double values.

+ * + *

If any value is NaN, NaN is + * returned. Infinity is handled.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the largest of the values + * @see IEEE754rUtils#max(double, double, double) for a version of this method that handles NaN differently + */ + public static double max(final double a, final double b, final double c) { + return Math.max(Math.max(a, b), c); + } + + /** + *

Gets the maximum of three float values.

+ * + *

If any value is NaN, NaN is + * returned. Infinity is handled.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the largest of the values + * @see IEEE754rUtils#max(float, float, float) for a version of this method that handles NaN differently + */ + public static float max(final float a, final float b, final float c) { + return Math.max(Math.max(a, b), c); + } + + //----------------------------------------------------------------------- + /** + *

Checks whether the String contains only + * digit characters.

+ * + *

Null and empty String will return + * false.

+ * + * @param str the String to check + * @return true if str contains only Unicode numeric + */ + public static boolean isDigits(final String str) { + return StringUtils.isNumeric(str); + } + + /** + *

Checks whether the String a valid Java number.

+ * + *

Valid numbers include hexadecimal marked with the 0x or + * 0X qualifier, octal numbers, scientific notation and + * numbers marked with a type qualifier (e.g. 123L).

+ * + *

Non-hexadecimal strings beginning with a leading zero are + * treated as octal values. Thus the string 09 will return + * false, since 9 is not a valid octal value. + * However, numbers beginning with {@code 0.} are treated as decimal.

+ * + *

null and empty/blank {@code String} will return + * false.

+ * + *

Note, {@link #createNumber(String)} should return a number for every + * input resuling in true.

+ * + * @param str the String to check + * @return true if the string is a correctly formatted number + * @since 3.3 the code supports hex {@code 0Xhhh} an + * octal {@code 0ddd} validation + * @deprecated This feature will be removed in Lang 4.0, + * use {@link NumberUtils#isCreatable(String)} instead + */ + @Deprecated + public static boolean isNumber(final String str) { + return isCreatable(str); + } + + /** + *

Checks whether the String a valid Java number.

+ * + *

Valid numbers include hexadecimal marked with the 0x or + * 0X qualifier, octal numbers, scientific notation and + * numbers marked with a type qualifier (e.g. 123L).

+ * + *

Non-hexadecimal strings beginning with a leading zero are + * treated as octal values. Thus the string 09 will return + * false, since 9 is not a valid octal value. + * However, numbers beginning with {@code 0.} are treated as decimal.

+ * + *

null and empty/blank {@code String} will return + * false.

+ * + *

Note, {@link #createNumber(String)} should return a number for every + * input resuling in true.

+ * + * @param str the String to check + * @return true if the string is a correctly formatted number + * @since 3.5 the code supports the "+" suffix on numbers except for integers in Java 1.6 + */ + public static boolean isCreatable(final String str) { + if (StringUtils.isEmpty(str)) { + return false; + } + final char[] chars = str.toCharArray(); + int sz = chars.length; + boolean hasExp = false; + boolean hasDecPoint = false; + boolean allowSigns = false; + boolean foundDigit = false; + // deal with any possible sign up front + final int start = chars[0] == '-' || chars[0] == '+' ? 1 : 0; + final boolean hasLeadingPlusSign = start == 1 && chars[0] == '+'; + if (sz > start + 1 && chars[start] == '0') { // leading 0 + if (chars[start + 1] == 'x' || chars[start + 1] == 'X') { // leading 0x/0X + int i = start + 2; + if (i == sz) { + return false; // str == "0x" + } + // checking hex (it can't be anything else) + for (; i < chars.length; i++) { + if ((chars[i] < '0' || chars[i] > '9') + && (chars[i] < 'a' || chars[i] > 'f') + && (chars[i] < 'A' || chars[i] > 'F')) { + return false; + } + } + return true; + } else if (Character.isDigit(chars[start + 1])) { + // leading 0, but not hex, must be octal + int i = start + 1; + for (; i < chars.length; i++) { + if (chars[i] < '0' || chars[i] > '7') { + return false; + } + } + return true; + } + } + sz--; // don't want to loop to the last char, check it afterwords + // for type qualifiers + int i = start; + // loop to the next to last char or to the last char if we need another digit to + // make a valid number (e.g. chars[0..5] = "1234E") + while (i < sz || i < sz + 1 && allowSigns && !foundDigit) { + if (chars[i] >= '0' && chars[i] <= '9') { + foundDigit = true; + allowSigns = false; + + } else if (chars[i] == '.') { + if (hasDecPoint || hasExp) { + // two decimal points or dec in exponent + return false; + } + hasDecPoint = true; + } else if (chars[i] == 'e' || chars[i] == 'E') { + // we've already taken care of hex. + if (hasExp) { + // two E's + return false; + } + if (!foundDigit) { + return false; + } + hasExp = true; + allowSigns = true; + } else if (chars[i] == '+' || chars[i] == '-') { + if (!allowSigns) { + return false; + } + allowSigns = false; + foundDigit = false; // we need a digit after the E + } else { + return false; + } + i++; + } + if (i < chars.length) { + if (chars[i] >= '0' && chars[i] <= '9') { + if (SystemUtils.IS_JAVA_1_6 && hasLeadingPlusSign && !hasDecPoint) { + return false; + } + // no type qualifier, OK + return true; + } + if (chars[i] == 'e' || chars[i] == 'E') { + // can't have an E at the last byte + return false; + } + if (chars[i] == '.') { + if (hasDecPoint || hasExp) { + // two decimal points or dec in exponent + return false; + } + // single trailing decimal point after non-exponent is ok + return foundDigit; + } + if (!allowSigns + && (chars[i] == 'd' + || chars[i] == 'D' + || chars[i] == 'f' + || chars[i] == 'F')) { + return foundDigit; + } + if (chars[i] == 'l' + || chars[i] == 'L') { + // not allowing L with an exponent or decimal point + return foundDigit && !hasExp && !hasDecPoint; + } + // last character is illegal + return false; + } + // allowSigns is true iff the val ends in 'E' + // found digit it to make sure weird stuff like '.' and '1E-' doesn't pass + return !allowSigns && foundDigit; + } + + /** + *

Checks whether the given String is a parsable number.

+ * + *

Parsable numbers include those Strings understood by {@link Integer#parseInt(String)}, + * {@link Long#parseLong(String)}, {@link Float#parseFloat(String)} or + * {@link Double#parseDouble(String)}. This method can be used instead of catching {@link java.text.ParseException} + * when calling one of those methods.

+ * + *

Hexadecimal and scientific notations are not considered parsable. + * See {@link #isCreatable(String)} on those cases.

+ * + *

{@code Null} and empty String will return false.

+ * + * @param str the String to check. + * @return {@code true} if the string is a parsable number. + * @since 3.4 + */ + public static boolean isParsable(final String str) { + if (StringUtils.isEmpty(str)) { + return false; + } + if (str.charAt(str.length() - 1) == '.') { + return false; + } + if (str.charAt(0) == '-') { + if (str.length() == 1) { + return false; + } + return withDecimalsParsing(str, 1); + } else { + return withDecimalsParsing(str, 0); + } + } + + private static boolean withDecimalsParsing(final String str, final int beginIdx) { + int decimalPoints = 0; + for (int i = beginIdx; i < str.length(); i++) { + final boolean isDecimalPoint = str.charAt(i) == '.'; + if (isDecimalPoint) { + decimalPoints++; + } + if (decimalPoints > 1) { + return false; + } + if (!isDecimalPoint && !Character.isDigit(str.charAt(i))) { + return false; + } + } + return true; + } + + /** + *

Compares two {@code int} values numerically. This is the same functionality as provided in Java 7.

+ * + * @param x the first {@code int} to compare + * @param y the second {@code int} 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(int x, int y) { + if (x == y) { + return 0; + } + return x < y ? -1 : 1; + } + + /** + *

Compares to {@code long} values numerically. This is the same functionality as provided in Java 7.

+ * + * @param x the first {@code long} to compare + * @param y the second {@code long} 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(long x, long y) { + if (x == y) { + return 0; + } + return x < y ? -1 : 1; + } + + /** + *

Compares to {@code short} values numerically. This is the same functionality as provided in Java 7.

+ * + * @param x the first {@code short} to compare + * @param y the second {@code short} 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(short x, short y) { + if (x == y) { + return 0; + } + return x < y ? -1 : 1; + } + + /** + *

Compares two {@code byte} values numerically. This is the same functionality as provided in Java 7.

+ * + * @param x the first {@code byte} to compare + * @param y the second {@code byte} 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(byte x, byte y) { + return x - y; + } +} diff --git a/Java/commons-lang-NumberUtils_1116/metadata.json b/Java/commons-lang-NumberUtils_1116/metadata.json new file mode 100644 index 000000000..abe124202 --- /dev/null +++ b/Java/commons-lang-NumberUtils_1116/metadata.json @@ -0,0 +1,21 @@ +{ + "language": "java", + "id": "commons-lang-NumberUtils_1116", + "buggyPath": ".", + "referencePath": null, + "buildCommand": "mvn package -V -B -Denforcer.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true -Drat.skip=true -Dlicense.skip=true -Dfindbugs.skip=true -Dgpg.skip=true -Dskip.npm=true -Dskip.gulp=true -Dskip.bower=true -Drat.numUnapprovedLicenses=100 -DskipTests=true -DskipITs=true -Dtest=None -DfailIfNoTests=false", + "testCommand": "mvn test -V -B -Denforcer.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true -Drat.skip=true -Dlicense.skip=true -Dfindbugs.skip=true -Dgpg.skip=true -Dskip.npm=true -Dskip.gulp=true -Dskip.bower=true -Drat.numUnapprovedLicenses=100", + "categories": [ + "safety", + "npe" + ], + "npe": { + "filepath": "src/main/java/org/apache/commons/lang3/math/NumberUtils.java", + "line": 1126, + "npe_method": "validateArray", + "deref_field": "array", + "npe_class": "NumberUtils", + "repo": "commons-lang", + "bug_id": "NumberUtils_1116" + } +} diff --git a/Java/commons-lang-NumberUtils_1116/npe.json b/Java/commons-lang-NumberUtils_1116/npe.json new file mode 100644 index 000000000..eae7f5c43 --- /dev/null +++ b/Java/commons-lang-NumberUtils_1116/npe.json @@ -0,0 +1,7 @@ +{ + "filepath": "src/main/java/org/apache/commons/lang3/math/NumberUtils.java", + "line": 1126, + "npe_method": "validateArray", + "deref_field": "array", + "npe_class": "NumberUtils" +} \ No newline at end of file diff --git a/Java/commons-lang-NumberUtils_223/Dockerfile b/Java/commons-lang-NumberUtils_223/Dockerfile new file mode 100644 index 000000000..7b7fbe349 --- /dev/null +++ b/Java/commons-lang-NumberUtils_223/Dockerfile @@ -0,0 +1,18 @@ +FROM ghcr.io/kupl/starlab-benchmarks/java-base:commons-lang + +ENV TZ=Asia/Seoul + +COPY ./metadata.json . +COPY ./npe.json . +COPY ./buggy.java /tmp/buggy.java +RUN export BUGGY_PATH=$(cat metadata.json | jq -r ".npe.filepath") \ + && export BUGGY_LINE=$(cat metadata.json | jq -r ".npe.line") \ + && export BUGGY_MTHD=$(cat metadata.json | jq -r ".npe.npe_method") \ + && mv /tmp/buggy.java $BUGGY_PATH \ + && echo "[{\"filepath\": \"$BUGGY_PATH\", \"line\": $BUGGY_LINE, \"method_name\": \"$BUGGY_MTHD\"}]" | jq . > traces.json + +RUN git init . && git add -A + +RUN $(cat metadata.json | jq -r ".buildCommand") + +RUN $(cat metadata.json | jq -r ".testCommand"); if [ $? -eq 0 ]; then exit 1; fi diff --git a/Java/commons-lang-NumberUtils_223/buggy.java b/Java/commons-lang-NumberUtils_223/buggy.java new file mode 100644 index 000000000..81df6208c --- /dev/null +++ b/Java/commons-lang-NumberUtils_223/buggy.java @@ -0,0 +1,1654 @@ +/* + * 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 java.lang.reflect.Array; +import java.math.BigDecimal; +import java.math.BigInteger; + +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.SystemUtils; +import org.apache.commons.lang3.Validate; + +/** + *

Provides extra functionality for Java Number classes.

+ * + * @since 2.0 + */ +public class NumberUtils { + + /** Reusable Long constant for zero. */ + public static final Long LONG_ZERO = Long.valueOf(0L); + /** Reusable Long constant for one. */ + public static final Long LONG_ONE = Long.valueOf(1L); + /** Reusable Long constant for minus one. */ + public static final Long LONG_MINUS_ONE = Long.valueOf(-1L); + /** Reusable Integer constant for zero. */ + public static final Integer INTEGER_ZERO = Integer.valueOf(0); + /** Reusable Integer constant for one. */ + public static final Integer INTEGER_ONE = Integer.valueOf(1); + /** Reusable Integer constant for minus one. */ + public static final Integer INTEGER_MINUS_ONE = Integer.valueOf(-1); + /** Reusable Short constant for zero. */ + public static final Short SHORT_ZERO = Short.valueOf((short) 0); + /** Reusable Short constant for one. */ + public static final Short SHORT_ONE = Short.valueOf((short) 1); + /** Reusable Short constant for minus one. */ + public static final Short SHORT_MINUS_ONE = Short.valueOf((short) -1); + /** Reusable Byte constant for zero. */ + public static final Byte BYTE_ZERO = Byte.valueOf((byte) 0); + /** Reusable Byte constant for one. */ + public static final Byte BYTE_ONE = Byte.valueOf((byte) 1); + /** Reusable Byte constant for minus one. */ + public static final Byte BYTE_MINUS_ONE = Byte.valueOf((byte) -1); + /** Reusable Double constant for zero. */ + public static final Double DOUBLE_ZERO = Double.valueOf(0.0d); + /** Reusable Double constant for one. */ + public static final Double DOUBLE_ONE = Double.valueOf(1.0d); + /** Reusable Double constant for minus one. */ + public static final Double DOUBLE_MINUS_ONE = Double.valueOf(-1.0d); + /** Reusable Float constant for zero. */ + public static final Float FLOAT_ZERO = Float.valueOf(0.0f); + /** Reusable Float constant for one. */ + public static final Float FLOAT_ONE = Float.valueOf(1.0f); + /** Reusable Float constant for minus one. */ + public static final Float FLOAT_MINUS_ONE = Float.valueOf(-1.0f); + + /** + *

NumberUtils instances should NOT be constructed in standard programming. + * Instead, the class should be used as NumberUtils.toInt("6");.

+ * + *

This constructor is public to permit tools that require a JavaBean instance + * to operate.

+ */ + public NumberUtils() { + super(); + } + + //----------------------------------------------------------------------- + /** + *

Convert a String to an int, returning + * zero if the conversion fails.

+ * + *

If the string is null, zero is returned.

+ * + *
+     *   NumberUtils.toInt(null) = 0
+     *   NumberUtils.toInt("")   = 0
+     *   NumberUtils.toInt("1")  = 1
+     * 
+ * + * @param str the string to convert, may be null + * @return the int represented by the string, or zero if + * conversion fails + * @since 2.1 + */ + public static int toInt(final String str) { + return toInt(str, 0); + } + + /** + *

Convert a String to an int, returning a + * default value if the conversion fails.

+ * + *

If the string is null, the default value is returned.

+ * + *
+     *   NumberUtils.toInt(null, 1) = 1
+     *   NumberUtils.toInt("", 1)   = 1
+     *   NumberUtils.toInt("1", 0)  = 1
+     * 
+ * + * @param str the string to convert, may be null + * @param defaultValue the default value + * @return the int represented by the string, or the default if conversion fails + * @since 2.1 + */ + public static int toInt(final String str, final int defaultValue) { + if(str == null) { + return defaultValue; + } + try { + return Integer.parseInt(str); + } catch (final NumberFormatException nfe) { + return defaultValue; + } + } + + /** + *

Convert a String to a long, returning + * zero if the conversion fails.

+ * + *

If the string is null, zero is returned.

+ * + *
+     *   NumberUtils.toLong(null) = 0L
+     *   NumberUtils.toLong("")   = 0L
+     *   NumberUtils.toLong("1")  = 1L
+     * 
+ * + * @param str the string to convert, may be null + * @return the long represented by the string, or 0 if + * conversion fails + * @since 2.1 + */ + public static long toLong(final String str) { + return toLong(str, 0L); + } + + /** + *

Convert a String to a long, returning a + * default value if the conversion fails.

+ * + *

If the string is null, the default value is returned.

+ * + *
+     *   NumberUtils.toLong(null, 1L) = 1L
+     *   NumberUtils.toLong("", 1L)   = 1L
+     *   NumberUtils.toLong("1", 0L)  = 1L
+     * 
+ * + * @param str the string to convert, may be null + * @param defaultValue the default value + * @return the long represented by the string, or the default if conversion fails + * @since 2.1 + */ + public static long toLong(final String str, final long defaultValue) { + if (str == null) { + return defaultValue; + } + try { + return Long.parseLong(str); + } catch (final NumberFormatException nfe) { + return defaultValue; + } + } + + /** + *

Convert a String to a float, returning + * 0.0f if the conversion fails.

+ * + *

If the string str is null, + * 0.0f is returned.

+ * + *
+     *   NumberUtils.toFloat(null)   = 0.0f
+     *   NumberUtils.toFloat("")     = 0.0f
+     *   NumberUtils.toFloat("1.5")  = 1.5f
+     * 
+ * + * @param str the string to convert, may be null + * @return the float represented by the string, or 0.0f + * if conversion fails + * @since 2.1 + */ + public static float toFloat(final String str) { + return toFloat(str, 0.0f); + } + + /** + *

Convert a String to a float, returning a + * default value if the conversion fails.

+ * + *

If the string str is null, the default + * value is returned.

+ * + *
+     *   NumberUtils.toFloat(null, 1.1f)   = 1.0f
+     *   NumberUtils.toFloat("", 1.1f)     = 1.1f
+     *   NumberUtils.toFloat("1.5", 0.0f)  = 1.5f
+     * 
+ * + * @param str the string to convert, may be null + * @param defaultValue the default value + * @return the float represented by the string, or defaultValue + * if conversion fails + * @since 2.1 + */ +/** + *

Convert a String to a float, returning a + * default value if the conversion fails.

+ * + *

If the string str is null, the default + * value is returned.

+ * + *
+ * NumberUtils.toFloat(null, 1.1f)   = 1.0f
+ * NumberUtils.toFloat("", 1.1f)     = 1.1f
+ * NumberUtils.toFloat("1.5", 0.0f)  = 1.5f
+ * 
+ * + * @param str + * the string to convert, may be null + * @param defaultValue + * the default value + * @return the float represented by the string, or defaultValue +if conversion fails + * @since 2.1 + */ +public static float toFloat(final java.lang.String str, final float defaultValue) { + { + try { + return java.lang.Float.parseFloat(/* NPEX_NULL_EXP */ + str); + } catch (final java.lang.NumberFormatException nfe) { + return defaultValue; + } + } +} + + /** + *

Convert a String to a double, returning + * 0.0d if the conversion fails.

+ * + *

If the string str is null, + * 0.0d is returned.

+ * + *
+     *   NumberUtils.toDouble(null)   = 0.0d
+     *   NumberUtils.toDouble("")     = 0.0d
+     *   NumberUtils.toDouble("1.5")  = 1.5d
+     * 
+ * + * @param str the string to convert, may be null + * @return the double represented by the string, or 0.0d + * if conversion fails + * @since 2.1 + */ + public static double toDouble(final String str) { + return toDouble(str, 0.0d); + } + + /** + *

Convert a String to a double, returning a + * default value if the conversion fails.

+ * + *

If the string str is null, the default + * value is returned.

+ * + *
+     *   NumberUtils.toDouble(null, 1.1d)   = 1.1d
+     *   NumberUtils.toDouble("", 1.1d)     = 1.1d
+     *   NumberUtils.toDouble("1.5", 0.0d)  = 1.5d
+     * 
+ * + * @param str the string to convert, may be null + * @param defaultValue the default value + * @return the double represented by the string, or defaultValue + * if conversion fails + * @since 2.1 + */ + public static double toDouble(final String str, final double defaultValue) { + if (str == null) { + return defaultValue; + } + try { + return Double.parseDouble(str); + } catch (final NumberFormatException nfe) { + return defaultValue; + } + } + + //----------------------------------------------------------------------- + /** + *

Convert a String to a byte, returning + * zero if the conversion fails.

+ * + *

If the string is null, zero is returned.

+ * + *
+     *   NumberUtils.toByte(null) = 0
+     *   NumberUtils.toByte("")   = 0
+     *   NumberUtils.toByte("1")  = 1
+     * 
+ * + * @param str the string to convert, may be null + * @return the byte represented by the string, or zero if + * conversion fails + * @since 2.5 + */ + public static byte toByte(final String str) { + return toByte(str, (byte) 0); + } + + /** + *

Convert a String to a byte, returning a + * default value if the conversion fails.

+ * + *

If the string is null, the default value is returned.

+ * + *
+     *   NumberUtils.toByte(null, 1) = 1
+     *   NumberUtils.toByte("", 1)   = 1
+     *   NumberUtils.toByte("1", 0)  = 1
+     * 
+ * + * @param str the string to convert, may be null + * @param defaultValue the default value + * @return the byte represented by the string, or the default if conversion fails + * @since 2.5 + */ + public static byte toByte(final String str, final byte defaultValue) { + if(str == null) { + return defaultValue; + } + try { + return Byte.parseByte(str); + } catch (final NumberFormatException nfe) { + return defaultValue; + } + } + + /** + *

Convert a String to a short, returning + * zero if the conversion fails.

+ * + *

If the string is null, zero is returned.

+ * + *
+     *   NumberUtils.toShort(null) = 0
+     *   NumberUtils.toShort("")   = 0
+     *   NumberUtils.toShort("1")  = 1
+     * 
+ * + * @param str the string to convert, may be null + * @return the short represented by the string, or zero if + * conversion fails + * @since 2.5 + */ + public static short toShort(final String str) { + return toShort(str, (short) 0); + } + + /** + *

Convert a String to an short, returning a + * default value if the conversion fails.

+ * + *

If the string is null, the default value is returned.

+ * + *
+     *   NumberUtils.toShort(null, 1) = 1
+     *   NumberUtils.toShort("", 1)   = 1
+     *   NumberUtils.toShort("1", 0)  = 1
+     * 
+ * + * @param str the string to convert, may be null + * @param defaultValue the default value + * @return the short represented by the string, or the default if conversion fails + * @since 2.5 + */ + public static short toShort(final String str, final short defaultValue) { + if(str == null) { + return defaultValue; + } + try { + return Short.parseShort(str); + } catch (final NumberFormatException nfe) { + return defaultValue; + } + } + + //----------------------------------------------------------------------- + // must handle Long, Float, Integer, Float, Short, + // BigDecimal, BigInteger and Byte + // useful methods: + // Byte.decode(String) + // Byte.valueOf(String,int radix) + // Byte.valueOf(String) + // Double.valueOf(String) + // Float.valueOf(String) + // Float.valueOf(String) + // Integer.valueOf(String,int radix) + // Integer.valueOf(String) + // Integer.decode(String) + // Integer.getInteger(String) + // Integer.getInteger(String,int val) + // Integer.getInteger(String,Integer val) + // Integer.valueOf(String) + // Double.valueOf(String) + // new Byte(String) + // Long.valueOf(String) + // Long.getLong(String) + // Long.getLong(String,int) + // Long.getLong(String,Integer) + // Long.valueOf(String,int) + // Long.valueOf(String) + // Short.valueOf(String) + // Short.decode(String) + // Short.valueOf(String,int) + // Short.valueOf(String) + // new BigDecimal(String) + // new BigInteger(String) + // new BigInteger(String,int radix) + // Possible inputs: + // 45 45.5 45E7 4.5E7 Hex Oct Binary xxxF xxxD xxxf xxxd + // plus minus everything. Prolly more. A lot are not separable. + + /** + *

Turns a string value into a java.lang.Number.

+ * + *

If the string starts with {@code 0x} or {@code -0x} (lower or upper case) or {@code #} or {@code -#}, it + * will be interpreted as a hexadecimal Integer - or Long, if the number of digits after the + * prefix is more than 8 - or BigInteger if there are more than 16 digits. + *

+ *

Then, the value is examined for a type qualifier on the end, i.e. one of + * 'f','F','d','D','l','L'. If it is found, it starts + * trying to create successively larger types from the type specified + * until one is found that can represent the value.

+ * + *

If a type specifier is not found, it will check for a decimal point + * and then try successively larger types from Integer to + * BigInteger and from Float to + * BigDecimal.

+ * + *

+ * Integral values with a leading {@code 0} will be interpreted as octal; the returned number will + * be Integer, Long or BigDecimal as appropriate. + *

+ * + *

Returns null if the string is null.

+ * + *

This method does not trim the input string, i.e., strings with leading + * or trailing spaces will generate NumberFormatExceptions.

+ * + * @param str String containing a number, may be null + * @return Number created from the string (or null if the input is null) + * @throws NumberFormatException if the value cannot be converted + */ + public static Number createNumber(final String str) throws NumberFormatException { + if (str == null) { + return null; + } + if (StringUtils.isBlank(str)) { + throw new NumberFormatException("A blank string is not a valid number"); + } + // Need to deal with all possible hex prefixes here + final String[] hex_prefixes = {"0x", "0X", "-0x", "-0X", "#", "-#"}; + int pfxLen = 0; + for(final String pfx : hex_prefixes) { + if (str.startsWith(pfx)) { + pfxLen += pfx.length(); + break; + } + } + if (pfxLen > 0) { // we have a hex number + char firstSigDigit = 0; // strip leading zeroes + for(int i = pfxLen; i < str.length(); i++) { + firstSigDigit = str.charAt(i); + if (firstSigDigit == '0') { // count leading zeroes + pfxLen++; + } else { + break; + } + } + final int hexDigits = str.length() - pfxLen; + if (hexDigits > 16 || hexDigits == 16 && firstSigDigit > '7') { // too many for Long + return createBigInteger(str); + } + if (hexDigits > 8 || hexDigits == 8 && firstSigDigit > '7') { // too many for an int + return createLong(str); + } + return createInteger(str); + } + final char lastChar = str.charAt(str.length() - 1); + String mant; + String dec; + String exp; + final int decPos = str.indexOf('.'); + final int expPos = str.indexOf('e') + str.indexOf('E') + 1; // assumes both not present + // if both e and E are present, this is caught by the checks on expPos (which prevent IOOBE) + // and the parsing which will detect if e or E appear in a number due to using the wrong offset + + if (decPos > -1) { // there is a decimal point + if (expPos > -1) { // there is an exponent + if (expPos < decPos || expPos > str.length()) { // prevents double exponent causing IOOBE + throw new NumberFormatException(str + " is not a valid number."); + } + dec = str.substring(decPos + 1, expPos); + } else { + dec = str.substring(decPos + 1); + } + mant = getMantissa(str, decPos); + } else { + if (expPos > -1) { + if (expPos > str.length()) { // prevents double exponent causing IOOBE + throw new NumberFormatException(str + " is not a valid number."); + } + mant = getMantissa(str, expPos); + } else { + mant = getMantissa(str); + } + dec = null; + } + if (!Character.isDigit(lastChar) && lastChar != '.') { + if (expPos > -1 && expPos < str.length() - 1) { + exp = str.substring(expPos + 1, str.length() - 1); + } else { + exp = null; + } + //Requesting a specific type.. + final String numeric = str.substring(0, str.length() - 1); + final boolean allZeros = isAllZeros(mant) && isAllZeros(exp); + switch (lastChar) { + case 'l' : + case 'L' : + if (dec == null + && exp == null + && (numeric.charAt(0) == '-' && isDigits(numeric.substring(1)) || isDigits(numeric))) { + try { + return createLong(numeric); + } catch (final NumberFormatException nfe) { // NOPMD + // Too big for a long + } + return createBigInteger(numeric); + + } + throw new NumberFormatException(str + " is not a valid number."); + case 'f' : + case 'F' : + try { + final Float f = NumberUtils.createFloat(str); + if (!(f.isInfinite() || f.floatValue() == 0.0F && !allZeros)) { + //If it's too big for a float or the float value = 0 and the string + //has non-zeros in it, then float does not have the precision we want + return f; + } + + } catch (final NumberFormatException nfe) { // NOPMD + // ignore the bad number + } + //$FALL-THROUGH$ + case 'd' : + case 'D' : + try { + final Double d = NumberUtils.createDouble(str); + if (!(d.isInfinite() || d.floatValue() == 0.0D && !allZeros)) { + return d; + } + } catch (final NumberFormatException nfe) { // NOPMD + // ignore the bad number + } + try { + return createBigDecimal(numeric); + } catch (final NumberFormatException e) { // NOPMD + // ignore the bad number + } + //$FALL-THROUGH$ + default : + throw new NumberFormatException(str + " is not a valid number."); + + } + } + //User doesn't have a preference on the return type, so let's start + //small and go from there... + if (expPos > -1 && expPos < str.length() - 1) { + exp = str.substring(expPos + 1, str.length()); + } else { + exp = null; + } + if (dec == null && exp == null) { // no decimal point and no exponent + //Must be an Integer, Long, Biginteger + try { + return createInteger(str); + } catch (final NumberFormatException nfe) { // NOPMD + // ignore the bad number + } + try { + return createLong(str); + } catch (final NumberFormatException nfe) { // NOPMD + // ignore the bad number + } + return createBigInteger(str); + } + + //Must be a Float, Double, BigDecimal + final boolean allZeros = isAllZeros(mant) && isAllZeros(exp); + try { + final Float f = createFloat(str); + final Double d = createDouble(str); + if (!f.isInfinite() + && !(f.floatValue() == 0.0F && !allZeros) + && f.toString().equals(d.toString())) { + return f; + } + if (!d.isInfinite() && !(d.doubleValue() == 0.0D && !allZeros)) { + final BigDecimal b = createBigDecimal(str); + if (b.compareTo(BigDecimal.valueOf(d)) == 0) { + return d; + } + return b; + } + } catch (final NumberFormatException nfe) { // NOPMD + // ignore the bad number + } + return createBigDecimal(str); + } + + /** + *

Utility method for {@link #createNumber(java.lang.String)}.

+ * + *

Returns mantissa of the given number.

+ * + * @param str the string representation of the number + * @return mantissa of the given number + */ + private static String getMantissa(final String str) { + return getMantissa(str, str.length()); + } + + /** + *

Utility method for {@link #createNumber(java.lang.String)}.

+ * + *

Returns mantissa of the given number.

+ * + * @param str the string representation of the number + * @param stopPos the position of the exponent or decimal point + * @return mantissa of the given number + */ + private static String getMantissa(final String str, final int stopPos) { + final char firstChar = str.charAt(0); + final boolean hasSign = firstChar == '-' || firstChar == '+'; + + return hasSign ? str.substring(1, stopPos) : str.substring(0, stopPos); + } + + /** + *

Utility method for {@link #createNumber(java.lang.String)}.

+ * + *

Returns true if s is null.

+ * + * @param str the String to check + * @return if it is all zeros or null + */ + private static boolean isAllZeros(final String str) { + if (str == null) { + return true; + } + for (int i = str.length() - 1; i >= 0; i--) { + if (str.charAt(i) != '0') { + return false; + } + } + return str.length() > 0; + } + + //----------------------------------------------------------------------- + /** + *

Convert a String to a Float.

+ * + *

Returns null if the string is null.

+ * + * @param str a String to convert, may be null + * @return converted Float (or null if the input is null) + * @throws NumberFormatException if the value cannot be converted + */ + public static Float createFloat(final String str) { + if (str == null) { + return null; + } + return Float.valueOf(str); + } + + /** + *

Convert a String to a Double.

+ * + *

Returns null if the string is null.

+ * + * @param str a String to convert, may be null + * @return converted Double (or null if the input is null) + * @throws NumberFormatException if the value cannot be converted + */ + public static Double createDouble(final String str) { + if (str == null) { + return null; + } + return Double.valueOf(str); + } + + /** + *

Convert a String to a Integer, handling + * hex (0xhhhh) and octal (0dddd) notations. + * N.B. a leading zero means octal; spaces are not trimmed.

+ * + *

Returns null if the string is null.

+ * + * @param str a String to convert, may be null + * @return converted Integer (or null if the input is null) + * @throws NumberFormatException if the value cannot be converted + */ + public static Integer createInteger(final String str) { + if (str == null) { + return null; + } + // decode() handles 0xAABD and 0777 (hex and octal) as well. + return Integer.decode(str); + } + + /** + *

Convert a String to a Long; + * since 3.1 it handles hex (0Xhhhh) and octal (0ddd) notations. + * N.B. a leading zero means octal; spaces are not trimmed.

+ * + *

Returns null if the string is null.

+ * + * @param str a String to convert, may be null + * @return converted Long (or null if the input is null) + * @throws NumberFormatException if the value cannot be converted + */ + public static Long createLong(final String str) { + if (str == null) { + return null; + } + return Long.decode(str); + } + + /** + *

Convert a String to a BigInteger; + * since 3.2 it handles hex (0x or #) and octal (0) notations.

+ * + *

Returns null if the string is null.

+ * + * @param str a String to convert, may be null + * @return converted BigInteger (or null if the input is null) + * @throws NumberFormatException if the value cannot be converted + */ + public static BigInteger createBigInteger(final String str) { + if (str == null) { + return null; + } + int pos = 0; // offset within string + int radix = 10; + boolean negate = false; // need to negate later? + if (str.startsWith("-")) { + negate = true; + pos = 1; + } + if (str.startsWith("0x", pos) || str.startsWith("0X", pos)) { // hex + radix = 16; + pos += 2; + } else if (str.startsWith("#", pos)) { // alternative hex (allowed by Long/Integer) + radix = 16; + pos ++; + } else if (str.startsWith("0", pos) && str.length() > pos + 1) { // octal; so long as there are additional digits + radix = 8; + pos ++; + } // default is to treat as decimal + + final BigInteger value = new BigInteger(str.substring(pos), radix); + return negate ? value.negate() : value; + } + + /** + *

Convert a String to a BigDecimal.

+ * + *

Returns null if the string is null.

+ * + * @param str a String to convert, may be null + * @return converted BigDecimal (or null if the input is null) + * @throws NumberFormatException if the value cannot be converted + */ + public static BigDecimal createBigDecimal(final String str) { + if (str == null) { + return null; + } + // handle JDK1.3.1 bug where "" throws IndexOutOfBoundsException + if (StringUtils.isBlank(str)) { + throw new NumberFormatException("A blank string is not a valid number"); + } + if (str.trim().startsWith("--")) { + // this is protection for poorness in java.lang.BigDecimal. + // it accepts this as a legal value, but it does not appear + // to be in specification of class. OS X Java parses it to + // a wrong value. + throw new NumberFormatException(str + " is not a valid number."); + } + return new BigDecimal(str); + } + + // Min in array + //-------------------------------------------------------------------- + /** + *

Returns the minimum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the minimum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @since 3.4 Changed signature from min(long[]) to min(long...) + */ + public static long min(final long... array) { + // Validates input + validateArray(array); + + // Finds and returns min + long min = array[0]; + for (int i = 1; i < array.length; i++) { + if (array[i] < min) { + min = array[i]; + } + } + + return min; + } + + /** + *

Returns the minimum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the minimum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @since 3.4 Changed signature from min(int[]) to min(int...) + */ + public static int min(final int... array) { + // Validates input + validateArray(array); + + // Finds and returns min + int min = array[0]; + for (int j = 1; j < array.length; j++) { + if (array[j] < min) { + min = array[j]; + } + } + + return min; + } + + /** + *

Returns the minimum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the minimum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @since 3.4 Changed signature from min(short[]) to min(short...) + */ + public static short min(final short... array) { + // Validates input + validateArray(array); + + // Finds and returns min + short min = array[0]; + for (int i = 1; i < array.length; i++) { + if (array[i] < min) { + min = array[i]; + } + } + + return min; + } + + /** + *

Returns the minimum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the minimum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @since 3.4 Changed signature from min(byte[]) to min(byte...) + */ + public static byte min(final byte... array) { + // Validates input + validateArray(array); + + // Finds and returns min + byte min = array[0]; + for (int i = 1; i < array.length; i++) { + if (array[i] < min) { + min = array[i]; + } + } + + return min; + } + + /** + *

Returns the minimum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the minimum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @see IEEE754rUtils#min(double[]) IEEE754rUtils for a version of this method that handles NaN differently + * @since 3.4 Changed signature from min(double[]) to min(double...) + */ + public static double min(final double... array) { + // Validates input + validateArray(array); + + // Finds and returns min + double min = array[0]; + for (int i = 1; i < array.length; i++) { + if (Double.isNaN(array[i])) { + return Double.NaN; + } + if (array[i] < min) { + min = array[i]; + } + } + + return min; + } + + /** + *

Returns the minimum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the minimum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @see IEEE754rUtils#min(float[]) IEEE754rUtils for a version of this method that handles NaN differently + * @since 3.4 Changed signature from min(float[]) to min(float...) + */ + public static float min(final float... array) { + // Validates input + validateArray(array); + + // Finds and returns min + float min = array[0]; + for (int i = 1; i < array.length; i++) { + if (Float.isNaN(array[i])) { + return Float.NaN; + } + if (array[i] < min) { + min = array[i]; + } + } + + return min; + } + + // Max in array + //-------------------------------------------------------------------- + /** + *

Returns the maximum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the maximum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @since 3.4 Changed signature from max(long[]) to max(long...) + */ + public static long max(final long... array) { + // Validates input + validateArray(array); + + // Finds and returns max + long max = array[0]; + for (int j = 1; j < array.length; j++) { + if (array[j] > max) { + max = array[j]; + } + } + + return max; + } + + /** + *

Returns the maximum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the maximum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @since 3.4 Changed signature from max(int[]) to max(int...) + */ + public static int max(final int... array) { + // Validates input + validateArray(array); + + // Finds and returns max + int max = array[0]; + for (int j = 1; j < array.length; j++) { + if (array[j] > max) { + max = array[j]; + } + } + + return max; + } + + /** + *

Returns the maximum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the maximum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @since 3.4 Changed signature from max(short[]) to max(short...) + */ + public static short max(final short... array) { + // Validates input + validateArray(array); + + // Finds and returns max + short max = array[0]; + for (int i = 1; i < array.length; i++) { + if (array[i] > max) { + max = array[i]; + } + } + + return max; + } + + /** + *

Returns the maximum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the maximum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @since 3.4 Changed signature from max(byte[]) to max(byte...) + */ + public static byte max(final byte... array) { + // Validates input + validateArray(array); + + // Finds and returns max + byte max = array[0]; + for (int i = 1; i < array.length; i++) { + if (array[i] > max) { + max = array[i]; + } + } + + return max; + } + + /** + *

Returns the maximum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the maximum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @see IEEE754rUtils#max(double[]) IEEE754rUtils for a version of this method that handles NaN differently + * @since 3.4 Changed signature from max(double[]) to max(double...) + */ + public static double max(final double... array) { + // Validates input + validateArray(array); + + // Finds and returns max + double max = array[0]; + for (int j = 1; j < array.length; j++) { + if (Double.isNaN(array[j])) { + return Double.NaN; + } + if (array[j] > max) { + max = array[j]; + } + } + + return max; + } + + /** + *

Returns the maximum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the maximum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @see IEEE754rUtils#max(float[]) IEEE754rUtils for a version of this method that handles NaN differently + * @since 3.4 Changed signature from max(float[]) to max(float...) + */ + public static float max(final float... array) { + // Validates input + validateArray(array); + + // Finds and returns max + float max = array[0]; + for (int j = 1; j < array.length; j++) { + if (Float.isNaN(array[j])) { + return Float.NaN; + } + if (array[j] > max) { + max = array[j]; + } + } + + return max; + } + + /** + * Checks if the specified array is neither null nor empty. + * + * @param array the array to check + * @throws IllegalArgumentException if {@code array} is either {@code null} or empty + */ + private static void validateArray(final Object array) { + if (array == null) { + throw new IllegalArgumentException("The Array must not be null"); + } + Validate.isTrue(Array.getLength(array) != 0, "Array cannot be empty."); + } + + // 3 param min + //----------------------------------------------------------------------- + /** + *

Gets the minimum of three long values.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the smallest of the values + */ + public static long min(long a, final long b, final long c) { + if (b < a) { + a = b; + } + if (c < a) { + a = c; + } + return a; + } + + /** + *

Gets the minimum of three int values.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the smallest of the values + */ + public static int min(int a, final int b, final int c) { + if (b < a) { + a = b; + } + if (c < a) { + a = c; + } + return a; + } + + /** + *

Gets the minimum of three short values.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the smallest of the values + */ + public static short min(short a, final short b, final short c) { + if (b < a) { + a = b; + } + if (c < a) { + a = c; + } + return a; + } + + /** + *

Gets the minimum of three byte values.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the smallest of the values + */ + public static byte min(byte a, final byte b, final byte c) { + if (b < a) { + a = b; + } + if (c < a) { + a = c; + } + return a; + } + + /** + *

Gets the minimum of three double values.

+ * + *

If any value is NaN, NaN is + * returned. Infinity is handled.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the smallest of the values + * @see IEEE754rUtils#min(double, double, double) for a version of this method that handles NaN differently + */ + public static double min(final double a, final double b, final double c) { + return Math.min(Math.min(a, b), c); + } + + /** + *

Gets the minimum of three float values.

+ * + *

If any value is NaN, NaN is + * returned. Infinity is handled.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the smallest of the values + * @see IEEE754rUtils#min(float, float, float) for a version of this method that handles NaN differently + */ + public static float min(final float a, final float b, final float c) { + return Math.min(Math.min(a, b), c); + } + + // 3 param max + //----------------------------------------------------------------------- + /** + *

Gets the maximum of three long values.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the largest of the values + */ + public static long max(long a, final long b, final long c) { + if (b > a) { + a = b; + } + if (c > a) { + a = c; + } + return a; + } + + /** + *

Gets the maximum of three int values.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the largest of the values + */ + public static int max(int a, final int b, final int c) { + if (b > a) { + a = b; + } + if (c > a) { + a = c; + } + return a; + } + + /** + *

Gets the maximum of three short values.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the largest of the values + */ + public static short max(short a, final short b, final short c) { + if (b > a) { + a = b; + } + if (c > a) { + a = c; + } + return a; + } + + /** + *

Gets the maximum of three byte values.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the largest of the values + */ + public static byte max(byte a, final byte b, final byte c) { + if (b > a) { + a = b; + } + if (c > a) { + a = c; + } + return a; + } + + /** + *

Gets the maximum of three double values.

+ * + *

If any value is NaN, NaN is + * returned. Infinity is handled.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the largest of the values + * @see IEEE754rUtils#max(double, double, double) for a version of this method that handles NaN differently + */ + public static double max(final double a, final double b, final double c) { + return Math.max(Math.max(a, b), c); + } + + /** + *

Gets the maximum of three float values.

+ * + *

If any value is NaN, NaN is + * returned. Infinity is handled.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the largest of the values + * @see IEEE754rUtils#max(float, float, float) for a version of this method that handles NaN differently + */ + public static float max(final float a, final float b, final float c) { + return Math.max(Math.max(a, b), c); + } + + //----------------------------------------------------------------------- + /** + *

Checks whether the String contains only + * digit characters.

+ * + *

Null and empty String will return + * false.

+ * + * @param str the String to check + * @return true if str contains only Unicode numeric + */ + public static boolean isDigits(final String str) { + return StringUtils.isNumeric(str); + } + + /** + *

Checks whether the String a valid Java number.

+ * + *

Valid numbers include hexadecimal marked with the 0x or + * 0X qualifier, octal numbers, scientific notation and + * numbers marked with a type qualifier (e.g. 123L).

+ * + *

Non-hexadecimal strings beginning with a leading zero are + * treated as octal values. Thus the string 09 will return + * false, since 9 is not a valid octal value. + * However, numbers beginning with {@code 0.} are treated as decimal.

+ * + *

null and empty/blank {@code String} will return + * false.

+ * + *

Note, {@link #createNumber(String)} should return a number for every + * input resuling in true.

+ * + * @param str the String to check + * @return true if the string is a correctly formatted number + * @since 3.3 the code supports hex {@code 0Xhhh} an + * octal {@code 0ddd} validation + * @deprecated This feature will be removed in Lang 4.0, + * use {@link NumberUtils#isCreatable(String)} instead + */ + @Deprecated + public static boolean isNumber(final String str) { + return isCreatable(str); + } + + /** + *

Checks whether the String a valid Java number.

+ * + *

Valid numbers include hexadecimal marked with the 0x or + * 0X qualifier, octal numbers, scientific notation and + * numbers marked with a type qualifier (e.g. 123L).

+ * + *

Non-hexadecimal strings beginning with a leading zero are + * treated as octal values. Thus the string 09 will return + * false, since 9 is not a valid octal value. + * However, numbers beginning with {@code 0.} are treated as decimal.

+ * + *

null and empty/blank {@code String} will return + * false.

+ * + *

Note, {@link #createNumber(String)} should return a number for every + * input resuling in true.

+ * + * @param str the String to check + * @return true if the string is a correctly formatted number + * @since 3.5 the code supports the "+" suffix on numbers except for integers in Java 1.6 + */ + public static boolean isCreatable(final String str) { + if (StringUtils.isEmpty(str)) { + return false; + } + final char[] chars = str.toCharArray(); + int sz = chars.length; + boolean hasExp = false; + boolean hasDecPoint = false; + boolean allowSigns = false; + boolean foundDigit = false; + // deal with any possible sign up front + final int start = chars[0] == '-' || chars[0] == '+' ? 1 : 0; + final boolean hasLeadingPlusSign = start == 1 && chars[0] == '+'; + if (sz > start + 1 && chars[start] == '0') { // leading 0 + if (chars[start + 1] == 'x' || chars[start + 1] == 'X') { // leading 0x/0X + int i = start + 2; + if (i == sz) { + return false; // str == "0x" + } + // checking hex (it can't be anything else) + for (; i < chars.length; i++) { + if ((chars[i] < '0' || chars[i] > '9') + && (chars[i] < 'a' || chars[i] > 'f') + && (chars[i] < 'A' || chars[i] > 'F')) { + return false; + } + } + return true; + } else if (Character.isDigit(chars[start + 1])) { + // leading 0, but not hex, must be octal + int i = start + 1; + for (; i < chars.length; i++) { + if (chars[i] < '0' || chars[i] > '7') { + return false; + } + } + return true; + } + } + sz--; // don't want to loop to the last char, check it afterwords + // for type qualifiers + int i = start; + // loop to the next to last char or to the last char if we need another digit to + // make a valid number (e.g. chars[0..5] = "1234E") + while (i < sz || i < sz + 1 && allowSigns && !foundDigit) { + if (chars[i] >= '0' && chars[i] <= '9') { + foundDigit = true; + allowSigns = false; + + } else if (chars[i] == '.') { + if (hasDecPoint || hasExp) { + // two decimal points or dec in exponent + return false; + } + hasDecPoint = true; + } else if (chars[i] == 'e' || chars[i] == 'E') { + // we've already taken care of hex. + if (hasExp) { + // two E's + return false; + } + if (!foundDigit) { + return false; + } + hasExp = true; + allowSigns = true; + } else if (chars[i] == '+' || chars[i] == '-') { + if (!allowSigns) { + return false; + } + allowSigns = false; + foundDigit = false; // we need a digit after the E + } else { + return false; + } + i++; + } + if (i < chars.length) { + if (chars[i] >= '0' && chars[i] <= '9') { + if (SystemUtils.IS_JAVA_1_6 && hasLeadingPlusSign && !hasDecPoint) { + return false; + } + // no type qualifier, OK + return true; + } + if (chars[i] == 'e' || chars[i] == 'E') { + // can't have an E at the last byte + return false; + } + if (chars[i] == '.') { + if (hasDecPoint || hasExp) { + // two decimal points or dec in exponent + return false; + } + // single trailing decimal point after non-exponent is ok + return foundDigit; + } + if (!allowSigns + && (chars[i] == 'd' + || chars[i] == 'D' + || chars[i] == 'f' + || chars[i] == 'F')) { + return foundDigit; + } + if (chars[i] == 'l' + || chars[i] == 'L') { + // not allowing L with an exponent or decimal point + return foundDigit && !hasExp && !hasDecPoint; + } + // last character is illegal + return false; + } + // allowSigns is true iff the val ends in 'E' + // found digit it to make sure weird stuff like '.' and '1E-' doesn't pass + return !allowSigns && foundDigit; + } + + /** + *

Checks whether the given String is a parsable number.

+ * + *

Parsable numbers include those Strings understood by {@link Integer#parseInt(String)}, + * {@link Long#parseLong(String)}, {@link Float#parseFloat(String)} or + * {@link Double#parseDouble(String)}. This method can be used instead of catching {@link java.text.ParseException} + * when calling one of those methods.

+ * + *

Hexadecimal and scientific notations are not considered parsable. + * See {@link #isCreatable(String)} on those cases.

+ * + *

{@code Null} and empty String will return false.

+ * + * @param str the String to check. + * @return {@code true} if the string is a parsable number. + * @since 3.4 + */ + public static boolean isParsable(final String str) { + if (StringUtils.isEmpty(str)) { + return false; + } + if (str.charAt(str.length() - 1) == '.') { + return false; + } + if (str.charAt(0) == '-') { + if (str.length() == 1) { + return false; + } + return withDecimalsParsing(str, 1); + } else { + return withDecimalsParsing(str, 0); + } + } + + private static boolean withDecimalsParsing(final String str, final int beginIdx) { + int decimalPoints = 0; + for (int i = beginIdx; i < str.length(); i++) { + final boolean isDecimalPoint = str.charAt(i) == '.'; + if (isDecimalPoint) { + decimalPoints++; + } + if (decimalPoints > 1) { + return false; + } + if (!isDecimalPoint && !Character.isDigit(str.charAt(i))) { + return false; + } + } + return true; + } + + /** + *

Compares two {@code int} values numerically. This is the same functionality as provided in Java 7.

+ * + * @param x the first {@code int} to compare + * @param y the second {@code int} 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(int x, int y) { + if (x == y) { + return 0; + } + return x < y ? -1 : 1; + } + + /** + *

Compares to {@code long} values numerically. This is the same functionality as provided in Java 7.

+ * + * @param x the first {@code long} to compare + * @param y the second {@code long} 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(long x, long y) { + if (x == y) { + return 0; + } + return x < y ? -1 : 1; + } + + /** + *

Compares to {@code short} values numerically. This is the same functionality as provided in Java 7.

+ * + * @param x the first {@code short} to compare + * @param y the second {@code short} 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(short x, short y) { + if (x == y) { + return 0; + } + return x < y ? -1 : 1; + } + + /** + *

Compares two {@code byte} values numerically. This is the same functionality as provided in Java 7.

+ * + * @param x the first {@code byte} to compare + * @param y the second {@code byte} 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(byte x, byte y) { + return x - y; + } +} diff --git a/Java/commons-lang-NumberUtils_223/metadata.json b/Java/commons-lang-NumberUtils_223/metadata.json new file mode 100644 index 000000000..eb3fb9d18 --- /dev/null +++ b/Java/commons-lang-NumberUtils_223/metadata.json @@ -0,0 +1,21 @@ +{ + "language": "java", + "id": "commons-lang-NumberUtils_223", + "buggyPath": ".", + "referencePath": null, + "buildCommand": "mvn package -V -B -Denforcer.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true -Drat.skip=true -Dlicense.skip=true -Dfindbugs.skip=true -Dgpg.skip=true -Dskip.npm=true -Dskip.gulp=true -Dskip.bower=true -Drat.numUnapprovedLicenses=100 -DskipTests=true -DskipITs=true -Dtest=None -DfailIfNoTests=false", + "testCommand": "mvn test -V -B -Denforcer.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true -Drat.skip=true -Dlicense.skip=true -Dfindbugs.skip=true -Dgpg.skip=true -Dskip.npm=true -Dskip.gulp=true -Dskip.bower=true -Drat.numUnapprovedLicenses=100", + "categories": [ + "safety", + "npe" + ], + "npe": { + "filepath": "src/main/java/org/apache/commons/lang3/math/NumberUtils.java", + "line": 247, + "npe_method": "toFloat", + "deref_field": "str", + "npe_class": "NumberUtils", + "repo": "commons-lang", + "bug_id": "NumberUtils_223" + } +} diff --git a/Java/commons-lang-NumberUtils_223/npe.json b/Java/commons-lang-NumberUtils_223/npe.json new file mode 100644 index 000000000..8aa362b01 --- /dev/null +++ b/Java/commons-lang-NumberUtils_223/npe.json @@ -0,0 +1,7 @@ +{ + "filepath": "src/main/java/org/apache/commons/lang3/math/NumberUtils.java", + "line": 247, + "npe_method": "toFloat", + "deref_field": "str", + "npe_class": "NumberUtils" +} \ No newline at end of file diff --git a/Java/commons-lang-NumberUtils_275/Dockerfile b/Java/commons-lang-NumberUtils_275/Dockerfile new file mode 100644 index 000000000..7b7fbe349 --- /dev/null +++ b/Java/commons-lang-NumberUtils_275/Dockerfile @@ -0,0 +1,18 @@ +FROM ghcr.io/kupl/starlab-benchmarks/java-base:commons-lang + +ENV TZ=Asia/Seoul + +COPY ./metadata.json . +COPY ./npe.json . +COPY ./buggy.java /tmp/buggy.java +RUN export BUGGY_PATH=$(cat metadata.json | jq -r ".npe.filepath") \ + && export BUGGY_LINE=$(cat metadata.json | jq -r ".npe.line") \ + && export BUGGY_MTHD=$(cat metadata.json | jq -r ".npe.npe_method") \ + && mv /tmp/buggy.java $BUGGY_PATH \ + && echo "[{\"filepath\": \"$BUGGY_PATH\", \"line\": $BUGGY_LINE, \"method_name\": \"$BUGGY_MTHD\"}]" | jq . > traces.json + +RUN git init . && git add -A + +RUN $(cat metadata.json | jq -r ".buildCommand") + +RUN $(cat metadata.json | jq -r ".testCommand"); if [ $? -eq 0 ]; then exit 1; fi diff --git a/Java/commons-lang-NumberUtils_275/buggy.java b/Java/commons-lang-NumberUtils_275/buggy.java new file mode 100644 index 000000000..f8b407bf9 --- /dev/null +++ b/Java/commons-lang-NumberUtils_275/buggy.java @@ -0,0 +1,1654 @@ +/* + * 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 java.lang.reflect.Array; +import java.math.BigDecimal; +import java.math.BigInteger; + +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.SystemUtils; +import org.apache.commons.lang3.Validate; + +/** + *

Provides extra functionality for Java Number classes.

+ * + * @since 2.0 + */ +public class NumberUtils { + + /** Reusable Long constant for zero. */ + public static final Long LONG_ZERO = Long.valueOf(0L); + /** Reusable Long constant for one. */ + public static final Long LONG_ONE = Long.valueOf(1L); + /** Reusable Long constant for minus one. */ + public static final Long LONG_MINUS_ONE = Long.valueOf(-1L); + /** Reusable Integer constant for zero. */ + public static final Integer INTEGER_ZERO = Integer.valueOf(0); + /** Reusable Integer constant for one. */ + public static final Integer INTEGER_ONE = Integer.valueOf(1); + /** Reusable Integer constant for minus one. */ + public static final Integer INTEGER_MINUS_ONE = Integer.valueOf(-1); + /** Reusable Short constant for zero. */ + public static final Short SHORT_ZERO = Short.valueOf((short) 0); + /** Reusable Short constant for one. */ + public static final Short SHORT_ONE = Short.valueOf((short) 1); + /** Reusable Short constant for minus one. */ + public static final Short SHORT_MINUS_ONE = Short.valueOf((short) -1); + /** Reusable Byte constant for zero. */ + public static final Byte BYTE_ZERO = Byte.valueOf((byte) 0); + /** Reusable Byte constant for one. */ + public static final Byte BYTE_ONE = Byte.valueOf((byte) 1); + /** Reusable Byte constant for minus one. */ + public static final Byte BYTE_MINUS_ONE = Byte.valueOf((byte) -1); + /** Reusable Double constant for zero. */ + public static final Double DOUBLE_ZERO = Double.valueOf(0.0d); + /** Reusable Double constant for one. */ + public static final Double DOUBLE_ONE = Double.valueOf(1.0d); + /** Reusable Double constant for minus one. */ + public static final Double DOUBLE_MINUS_ONE = Double.valueOf(-1.0d); + /** Reusable Float constant for zero. */ + public static final Float FLOAT_ZERO = Float.valueOf(0.0f); + /** Reusable Float constant for one. */ + public static final Float FLOAT_ONE = Float.valueOf(1.0f); + /** Reusable Float constant for minus one. */ + public static final Float FLOAT_MINUS_ONE = Float.valueOf(-1.0f); + + /** + *

NumberUtils instances should NOT be constructed in standard programming. + * Instead, the class should be used as NumberUtils.toInt("6");.

+ * + *

This constructor is public to permit tools that require a JavaBean instance + * to operate.

+ */ + public NumberUtils() { + super(); + } + + //----------------------------------------------------------------------- + /** + *

Convert a String to an int, returning + * zero if the conversion fails.

+ * + *

If the string is null, zero is returned.

+ * + *
+     *   NumberUtils.toInt(null) = 0
+     *   NumberUtils.toInt("")   = 0
+     *   NumberUtils.toInt("1")  = 1
+     * 
+ * + * @param str the string to convert, may be null + * @return the int represented by the string, or zero if + * conversion fails + * @since 2.1 + */ + public static int toInt(final String str) { + return toInt(str, 0); + } + + /** + *

Convert a String to an int, returning a + * default value if the conversion fails.

+ * + *

If the string is null, the default value is returned.

+ * + *
+     *   NumberUtils.toInt(null, 1) = 1
+     *   NumberUtils.toInt("", 1)   = 1
+     *   NumberUtils.toInt("1", 0)  = 1
+     * 
+ * + * @param str the string to convert, may be null + * @param defaultValue the default value + * @return the int represented by the string, or the default if conversion fails + * @since 2.1 + */ + public static int toInt(final String str, final int defaultValue) { + if(str == null) { + return defaultValue; + } + try { + return Integer.parseInt(str); + } catch (final NumberFormatException nfe) { + return defaultValue; + } + } + + /** + *

Convert a String to a long, returning + * zero if the conversion fails.

+ * + *

If the string is null, zero is returned.

+ * + *
+     *   NumberUtils.toLong(null) = 0L
+     *   NumberUtils.toLong("")   = 0L
+     *   NumberUtils.toLong("1")  = 1L
+     * 
+ * + * @param str the string to convert, may be null + * @return the long represented by the string, or 0 if + * conversion fails + * @since 2.1 + */ + public static long toLong(final String str) { + return toLong(str, 0L); + } + + /** + *

Convert a String to a long, returning a + * default value if the conversion fails.

+ * + *

If the string is null, the default value is returned.

+ * + *
+     *   NumberUtils.toLong(null, 1L) = 1L
+     *   NumberUtils.toLong("", 1L)   = 1L
+     *   NumberUtils.toLong("1", 0L)  = 1L
+     * 
+ * + * @param str the string to convert, may be null + * @param defaultValue the default value + * @return the long represented by the string, or the default if conversion fails + * @since 2.1 + */ + public static long toLong(final String str, final long defaultValue) { + if (str == null) { + return defaultValue; + } + try { + return Long.parseLong(str); + } catch (final NumberFormatException nfe) { + return defaultValue; + } + } + + /** + *

Convert a String to a float, returning + * 0.0f if the conversion fails.

+ * + *

If the string str is null, + * 0.0f is returned.

+ * + *
+     *   NumberUtils.toFloat(null)   = 0.0f
+     *   NumberUtils.toFloat("")     = 0.0f
+     *   NumberUtils.toFloat("1.5")  = 1.5f
+     * 
+ * + * @param str the string to convert, may be null + * @return the float represented by the string, or 0.0f + * if conversion fails + * @since 2.1 + */ + public static float toFloat(final String str) { + return toFloat(str, 0.0f); + } + + /** + *

Convert a String to a float, returning a + * default value if the conversion fails.

+ * + *

If the string str is null, the default + * value is returned.

+ * + *
+     *   NumberUtils.toFloat(null, 1.1f)   = 1.0f
+     *   NumberUtils.toFloat("", 1.1f)     = 1.1f
+     *   NumberUtils.toFloat("1.5", 0.0f)  = 1.5f
+     * 
+ * + * @param str the string to convert, may be null + * @param defaultValue the default value + * @return the float represented by the string, or defaultValue + * if conversion fails + * @since 2.1 + */ + public static float toFloat(final String str, final float defaultValue) { + if (str == null) { + return defaultValue; + } + try { + return Float.parseFloat(str); + } catch (final NumberFormatException nfe) { + return defaultValue; + } + } + + /** + *

Convert a String to a double, returning + * 0.0d if the conversion fails.

+ * + *

If the string str is null, + * 0.0d is returned.

+ * + *
+     *   NumberUtils.toDouble(null)   = 0.0d
+     *   NumberUtils.toDouble("")     = 0.0d
+     *   NumberUtils.toDouble("1.5")  = 1.5d
+     * 
+ * + * @param str the string to convert, may be null + * @return the double represented by the string, or 0.0d + * if conversion fails + * @since 2.1 + */ + public static double toDouble(final String str) { + return toDouble(str, 0.0d); + } + + /** + *

Convert a String to a double, returning a + * default value if the conversion fails.

+ * + *

If the string str is null, the default + * value is returned.

+ * + *
+     *   NumberUtils.toDouble(null, 1.1d)   = 1.1d
+     *   NumberUtils.toDouble("", 1.1d)     = 1.1d
+     *   NumberUtils.toDouble("1.5", 0.0d)  = 1.5d
+     * 
+ * + * @param str the string to convert, may be null + * @param defaultValue the default value + * @return the double represented by the string, or defaultValue + * if conversion fails + * @since 2.1 + */ +/** + *

Convert a String to a double, returning a + * default value if the conversion fails.

+ * + *

If the string str is null, the default + * value is returned.

+ * + *
+ * NumberUtils.toDouble(null, 1.1d)   = 1.1d
+ * NumberUtils.toDouble("", 1.1d)     = 1.1d
+ * NumberUtils.toDouble("1.5", 0.0d)  = 1.5d
+ * 
+ * + * @param str + * the string to convert, may be null + * @param defaultValue + * the default value + * @return the double represented by the string, or defaultValue +if conversion fails + * @since 2.1 + */ +public static double toDouble(final java.lang.String str, final double defaultValue) { + { + try { + return java.lang.Double.parseDouble(/* NPEX_NULL_EXP */ + str); + } catch (final java.lang.NumberFormatException nfe) { + return defaultValue; + } + } +} + + //----------------------------------------------------------------------- + /** + *

Convert a String to a byte, returning + * zero if the conversion fails.

+ * + *

If the string is null, zero is returned.

+ * + *
+     *   NumberUtils.toByte(null) = 0
+     *   NumberUtils.toByte("")   = 0
+     *   NumberUtils.toByte("1")  = 1
+     * 
+ * + * @param str the string to convert, may be null + * @return the byte represented by the string, or zero if + * conversion fails + * @since 2.5 + */ + public static byte toByte(final String str) { + return toByte(str, (byte) 0); + } + + /** + *

Convert a String to a byte, returning a + * default value if the conversion fails.

+ * + *

If the string is null, the default value is returned.

+ * + *
+     *   NumberUtils.toByte(null, 1) = 1
+     *   NumberUtils.toByte("", 1)   = 1
+     *   NumberUtils.toByte("1", 0)  = 1
+     * 
+ * + * @param str the string to convert, may be null + * @param defaultValue the default value + * @return the byte represented by the string, or the default if conversion fails + * @since 2.5 + */ + public static byte toByte(final String str, final byte defaultValue) { + if(str == null) { + return defaultValue; + } + try { + return Byte.parseByte(str); + } catch (final NumberFormatException nfe) { + return defaultValue; + } + } + + /** + *

Convert a String to a short, returning + * zero if the conversion fails.

+ * + *

If the string is null, zero is returned.

+ * + *
+     *   NumberUtils.toShort(null) = 0
+     *   NumberUtils.toShort("")   = 0
+     *   NumberUtils.toShort("1")  = 1
+     * 
+ * + * @param str the string to convert, may be null + * @return the short represented by the string, or zero if + * conversion fails + * @since 2.5 + */ + public static short toShort(final String str) { + return toShort(str, (short) 0); + } + + /** + *

Convert a String to an short, returning a + * default value if the conversion fails.

+ * + *

If the string is null, the default value is returned.

+ * + *
+     *   NumberUtils.toShort(null, 1) = 1
+     *   NumberUtils.toShort("", 1)   = 1
+     *   NumberUtils.toShort("1", 0)  = 1
+     * 
+ * + * @param str the string to convert, may be null + * @param defaultValue the default value + * @return the short represented by the string, or the default if conversion fails + * @since 2.5 + */ + public static short toShort(final String str, final short defaultValue) { + if(str == null) { + return defaultValue; + } + try { + return Short.parseShort(str); + } catch (final NumberFormatException nfe) { + return defaultValue; + } + } + + //----------------------------------------------------------------------- + // must handle Long, Float, Integer, Float, Short, + // BigDecimal, BigInteger and Byte + // useful methods: + // Byte.decode(String) + // Byte.valueOf(String,int radix) + // Byte.valueOf(String) + // Double.valueOf(String) + // Float.valueOf(String) + // Float.valueOf(String) + // Integer.valueOf(String,int radix) + // Integer.valueOf(String) + // Integer.decode(String) + // Integer.getInteger(String) + // Integer.getInteger(String,int val) + // Integer.getInteger(String,Integer val) + // Integer.valueOf(String) + // Double.valueOf(String) + // new Byte(String) + // Long.valueOf(String) + // Long.getLong(String) + // Long.getLong(String,int) + // Long.getLong(String,Integer) + // Long.valueOf(String,int) + // Long.valueOf(String) + // Short.valueOf(String) + // Short.decode(String) + // Short.valueOf(String,int) + // Short.valueOf(String) + // new BigDecimal(String) + // new BigInteger(String) + // new BigInteger(String,int radix) + // Possible inputs: + // 45 45.5 45E7 4.5E7 Hex Oct Binary xxxF xxxD xxxf xxxd + // plus minus everything. Prolly more. A lot are not separable. + + /** + *

Turns a string value into a java.lang.Number.

+ * + *

If the string starts with {@code 0x} or {@code -0x} (lower or upper case) or {@code #} or {@code -#}, it + * will be interpreted as a hexadecimal Integer - or Long, if the number of digits after the + * prefix is more than 8 - or BigInteger if there are more than 16 digits. + *

+ *

Then, the value is examined for a type qualifier on the end, i.e. one of + * 'f','F','d','D','l','L'. If it is found, it starts + * trying to create successively larger types from the type specified + * until one is found that can represent the value.

+ * + *

If a type specifier is not found, it will check for a decimal point + * and then try successively larger types from Integer to + * BigInteger and from Float to + * BigDecimal.

+ * + *

+ * Integral values with a leading {@code 0} will be interpreted as octal; the returned number will + * be Integer, Long or BigDecimal as appropriate. + *

+ * + *

Returns null if the string is null.

+ * + *

This method does not trim the input string, i.e., strings with leading + * or trailing spaces will generate NumberFormatExceptions.

+ * + * @param str String containing a number, may be null + * @return Number created from the string (or null if the input is null) + * @throws NumberFormatException if the value cannot be converted + */ + public static Number createNumber(final String str) throws NumberFormatException { + if (str == null) { + return null; + } + if (StringUtils.isBlank(str)) { + throw new NumberFormatException("A blank string is not a valid number"); + } + // Need to deal with all possible hex prefixes here + final String[] hex_prefixes = {"0x", "0X", "-0x", "-0X", "#", "-#"}; + int pfxLen = 0; + for(final String pfx : hex_prefixes) { + if (str.startsWith(pfx)) { + pfxLen += pfx.length(); + break; + } + } + if (pfxLen > 0) { // we have a hex number + char firstSigDigit = 0; // strip leading zeroes + for(int i = pfxLen; i < str.length(); i++) { + firstSigDigit = str.charAt(i); + if (firstSigDigit == '0') { // count leading zeroes + pfxLen++; + } else { + break; + } + } + final int hexDigits = str.length() - pfxLen; + if (hexDigits > 16 || hexDigits == 16 && firstSigDigit > '7') { // too many for Long + return createBigInteger(str); + } + if (hexDigits > 8 || hexDigits == 8 && firstSigDigit > '7') { // too many for an int + return createLong(str); + } + return createInteger(str); + } + final char lastChar = str.charAt(str.length() - 1); + String mant; + String dec; + String exp; + final int decPos = str.indexOf('.'); + final int expPos = str.indexOf('e') + str.indexOf('E') + 1; // assumes both not present + // if both e and E are present, this is caught by the checks on expPos (which prevent IOOBE) + // and the parsing which will detect if e or E appear in a number due to using the wrong offset + + if (decPos > -1) { // there is a decimal point + if (expPos > -1) { // there is an exponent + if (expPos < decPos || expPos > str.length()) { // prevents double exponent causing IOOBE + throw new NumberFormatException(str + " is not a valid number."); + } + dec = str.substring(decPos + 1, expPos); + } else { + dec = str.substring(decPos + 1); + } + mant = getMantissa(str, decPos); + } else { + if (expPos > -1) { + if (expPos > str.length()) { // prevents double exponent causing IOOBE + throw new NumberFormatException(str + " is not a valid number."); + } + mant = getMantissa(str, expPos); + } else { + mant = getMantissa(str); + } + dec = null; + } + if (!Character.isDigit(lastChar) && lastChar != '.') { + if (expPos > -1 && expPos < str.length() - 1) { + exp = str.substring(expPos + 1, str.length() - 1); + } else { + exp = null; + } + //Requesting a specific type.. + final String numeric = str.substring(0, str.length() - 1); + final boolean allZeros = isAllZeros(mant) && isAllZeros(exp); + switch (lastChar) { + case 'l' : + case 'L' : + if (dec == null + && exp == null + && (numeric.charAt(0) == '-' && isDigits(numeric.substring(1)) || isDigits(numeric))) { + try { + return createLong(numeric); + } catch (final NumberFormatException nfe) { // NOPMD + // Too big for a long + } + return createBigInteger(numeric); + + } + throw new NumberFormatException(str + " is not a valid number."); + case 'f' : + case 'F' : + try { + final Float f = NumberUtils.createFloat(str); + if (!(f.isInfinite() || f.floatValue() == 0.0F && !allZeros)) { + //If it's too big for a float or the float value = 0 and the string + //has non-zeros in it, then float does not have the precision we want + return f; + } + + } catch (final NumberFormatException nfe) { // NOPMD + // ignore the bad number + } + //$FALL-THROUGH$ + case 'd' : + case 'D' : + try { + final Double d = NumberUtils.createDouble(str); + if (!(d.isInfinite() || d.floatValue() == 0.0D && !allZeros)) { + return d; + } + } catch (final NumberFormatException nfe) { // NOPMD + // ignore the bad number + } + try { + return createBigDecimal(numeric); + } catch (final NumberFormatException e) { // NOPMD + // ignore the bad number + } + //$FALL-THROUGH$ + default : + throw new NumberFormatException(str + " is not a valid number."); + + } + } + //User doesn't have a preference on the return type, so let's start + //small and go from there... + if (expPos > -1 && expPos < str.length() - 1) { + exp = str.substring(expPos + 1, str.length()); + } else { + exp = null; + } + if (dec == null && exp == null) { // no decimal point and no exponent + //Must be an Integer, Long, Biginteger + try { + return createInteger(str); + } catch (final NumberFormatException nfe) { // NOPMD + // ignore the bad number + } + try { + return createLong(str); + } catch (final NumberFormatException nfe) { // NOPMD + // ignore the bad number + } + return createBigInteger(str); + } + + //Must be a Float, Double, BigDecimal + final boolean allZeros = isAllZeros(mant) && isAllZeros(exp); + try { + final Float f = createFloat(str); + final Double d = createDouble(str); + if (!f.isInfinite() + && !(f.floatValue() == 0.0F && !allZeros) + && f.toString().equals(d.toString())) { + return f; + } + if (!d.isInfinite() && !(d.doubleValue() == 0.0D && !allZeros)) { + final BigDecimal b = createBigDecimal(str); + if (b.compareTo(BigDecimal.valueOf(d)) == 0) { + return d; + } + return b; + } + } catch (final NumberFormatException nfe) { // NOPMD + // ignore the bad number + } + return createBigDecimal(str); + } + + /** + *

Utility method for {@link #createNumber(java.lang.String)}.

+ * + *

Returns mantissa of the given number.

+ * + * @param str the string representation of the number + * @return mantissa of the given number + */ + private static String getMantissa(final String str) { + return getMantissa(str, str.length()); + } + + /** + *

Utility method for {@link #createNumber(java.lang.String)}.

+ * + *

Returns mantissa of the given number.

+ * + * @param str the string representation of the number + * @param stopPos the position of the exponent or decimal point + * @return mantissa of the given number + */ + private static String getMantissa(final String str, final int stopPos) { + final char firstChar = str.charAt(0); + final boolean hasSign = firstChar == '-' || firstChar == '+'; + + return hasSign ? str.substring(1, stopPos) : str.substring(0, stopPos); + } + + /** + *

Utility method for {@link #createNumber(java.lang.String)}.

+ * + *

Returns true if s is null.

+ * + * @param str the String to check + * @return if it is all zeros or null + */ + private static boolean isAllZeros(final String str) { + if (str == null) { + return true; + } + for (int i = str.length() - 1; i >= 0; i--) { + if (str.charAt(i) != '0') { + return false; + } + } + return str.length() > 0; + } + + //----------------------------------------------------------------------- + /** + *

Convert a String to a Float.

+ * + *

Returns null if the string is null.

+ * + * @param str a String to convert, may be null + * @return converted Float (or null if the input is null) + * @throws NumberFormatException if the value cannot be converted + */ + public static Float createFloat(final String str) { + if (str == null) { + return null; + } + return Float.valueOf(str); + } + + /** + *

Convert a String to a Double.

+ * + *

Returns null if the string is null.

+ * + * @param str a String to convert, may be null + * @return converted Double (or null if the input is null) + * @throws NumberFormatException if the value cannot be converted + */ + public static Double createDouble(final String str) { + if (str == null) { + return null; + } + return Double.valueOf(str); + } + + /** + *

Convert a String to a Integer, handling + * hex (0xhhhh) and octal (0dddd) notations. + * N.B. a leading zero means octal; spaces are not trimmed.

+ * + *

Returns null if the string is null.

+ * + * @param str a String to convert, may be null + * @return converted Integer (or null if the input is null) + * @throws NumberFormatException if the value cannot be converted + */ + public static Integer createInteger(final String str) { + if (str == null) { + return null; + } + // decode() handles 0xAABD and 0777 (hex and octal) as well. + return Integer.decode(str); + } + + /** + *

Convert a String to a Long; + * since 3.1 it handles hex (0Xhhhh) and octal (0ddd) notations. + * N.B. a leading zero means octal; spaces are not trimmed.

+ * + *

Returns null if the string is null.

+ * + * @param str a String to convert, may be null + * @return converted Long (or null if the input is null) + * @throws NumberFormatException if the value cannot be converted + */ + public static Long createLong(final String str) { + if (str == null) { + return null; + } + return Long.decode(str); + } + + /** + *

Convert a String to a BigInteger; + * since 3.2 it handles hex (0x or #) and octal (0) notations.

+ * + *

Returns null if the string is null.

+ * + * @param str a String to convert, may be null + * @return converted BigInteger (or null if the input is null) + * @throws NumberFormatException if the value cannot be converted + */ + public static BigInteger createBigInteger(final String str) { + if (str == null) { + return null; + } + int pos = 0; // offset within string + int radix = 10; + boolean negate = false; // need to negate later? + if (str.startsWith("-")) { + negate = true; + pos = 1; + } + if (str.startsWith("0x", pos) || str.startsWith("0X", pos)) { // hex + radix = 16; + pos += 2; + } else if (str.startsWith("#", pos)) { // alternative hex (allowed by Long/Integer) + radix = 16; + pos ++; + } else if (str.startsWith("0", pos) && str.length() > pos + 1) { // octal; so long as there are additional digits + radix = 8; + pos ++; + } // default is to treat as decimal + + final BigInteger value = new BigInteger(str.substring(pos), radix); + return negate ? value.negate() : value; + } + + /** + *

Convert a String to a BigDecimal.

+ * + *

Returns null if the string is null.

+ * + * @param str a String to convert, may be null + * @return converted BigDecimal (or null if the input is null) + * @throws NumberFormatException if the value cannot be converted + */ + public static BigDecimal createBigDecimal(final String str) { + if (str == null) { + return null; + } + // handle JDK1.3.1 bug where "" throws IndexOutOfBoundsException + if (StringUtils.isBlank(str)) { + throw new NumberFormatException("A blank string is not a valid number"); + } + if (str.trim().startsWith("--")) { + // this is protection for poorness in java.lang.BigDecimal. + // it accepts this as a legal value, but it does not appear + // to be in specification of class. OS X Java parses it to + // a wrong value. + throw new NumberFormatException(str + " is not a valid number."); + } + return new BigDecimal(str); + } + + // Min in array + //-------------------------------------------------------------------- + /** + *

Returns the minimum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the minimum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @since 3.4 Changed signature from min(long[]) to min(long...) + */ + public static long min(final long... array) { + // Validates input + validateArray(array); + + // Finds and returns min + long min = array[0]; + for (int i = 1; i < array.length; i++) { + if (array[i] < min) { + min = array[i]; + } + } + + return min; + } + + /** + *

Returns the minimum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the minimum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @since 3.4 Changed signature from min(int[]) to min(int...) + */ + public static int min(final int... array) { + // Validates input + validateArray(array); + + // Finds and returns min + int min = array[0]; + for (int j = 1; j < array.length; j++) { + if (array[j] < min) { + min = array[j]; + } + } + + return min; + } + + /** + *

Returns the minimum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the minimum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @since 3.4 Changed signature from min(short[]) to min(short...) + */ + public static short min(final short... array) { + // Validates input + validateArray(array); + + // Finds and returns min + short min = array[0]; + for (int i = 1; i < array.length; i++) { + if (array[i] < min) { + min = array[i]; + } + } + + return min; + } + + /** + *

Returns the minimum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the minimum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @since 3.4 Changed signature from min(byte[]) to min(byte...) + */ + public static byte min(final byte... array) { + // Validates input + validateArray(array); + + // Finds and returns min + byte min = array[0]; + for (int i = 1; i < array.length; i++) { + if (array[i] < min) { + min = array[i]; + } + } + + return min; + } + + /** + *

Returns the minimum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the minimum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @see IEEE754rUtils#min(double[]) IEEE754rUtils for a version of this method that handles NaN differently + * @since 3.4 Changed signature from min(double[]) to min(double...) + */ + public static double min(final double... array) { + // Validates input + validateArray(array); + + // Finds and returns min + double min = array[0]; + for (int i = 1; i < array.length; i++) { + if (Double.isNaN(array[i])) { + return Double.NaN; + } + if (array[i] < min) { + min = array[i]; + } + } + + return min; + } + + /** + *

Returns the minimum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the minimum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @see IEEE754rUtils#min(float[]) IEEE754rUtils for a version of this method that handles NaN differently + * @since 3.4 Changed signature from min(float[]) to min(float...) + */ + public static float min(final float... array) { + // Validates input + validateArray(array); + + // Finds and returns min + float min = array[0]; + for (int i = 1; i < array.length; i++) { + if (Float.isNaN(array[i])) { + return Float.NaN; + } + if (array[i] < min) { + min = array[i]; + } + } + + return min; + } + + // Max in array + //-------------------------------------------------------------------- + /** + *

Returns the maximum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the maximum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @since 3.4 Changed signature from max(long[]) to max(long...) + */ + public static long max(final long... array) { + // Validates input + validateArray(array); + + // Finds and returns max + long max = array[0]; + for (int j = 1; j < array.length; j++) { + if (array[j] > max) { + max = array[j]; + } + } + + return max; + } + + /** + *

Returns the maximum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the maximum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @since 3.4 Changed signature from max(int[]) to max(int...) + */ + public static int max(final int... array) { + // Validates input + validateArray(array); + + // Finds and returns max + int max = array[0]; + for (int j = 1; j < array.length; j++) { + if (array[j] > max) { + max = array[j]; + } + } + + return max; + } + + /** + *

Returns the maximum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the maximum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @since 3.4 Changed signature from max(short[]) to max(short...) + */ + public static short max(final short... array) { + // Validates input + validateArray(array); + + // Finds and returns max + short max = array[0]; + for (int i = 1; i < array.length; i++) { + if (array[i] > max) { + max = array[i]; + } + } + + return max; + } + + /** + *

Returns the maximum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the maximum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @since 3.4 Changed signature from max(byte[]) to max(byte...) + */ + public static byte max(final byte... array) { + // Validates input + validateArray(array); + + // Finds and returns max + byte max = array[0]; + for (int i = 1; i < array.length; i++) { + if (array[i] > max) { + max = array[i]; + } + } + + return max; + } + + /** + *

Returns the maximum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the maximum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @see IEEE754rUtils#max(double[]) IEEE754rUtils for a version of this method that handles NaN differently + * @since 3.4 Changed signature from max(double[]) to max(double...) + */ + public static double max(final double... array) { + // Validates input + validateArray(array); + + // Finds and returns max + double max = array[0]; + for (int j = 1; j < array.length; j++) { + if (Double.isNaN(array[j])) { + return Double.NaN; + } + if (array[j] > max) { + max = array[j]; + } + } + + return max; + } + + /** + *

Returns the maximum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the maximum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @see IEEE754rUtils#max(float[]) IEEE754rUtils for a version of this method that handles NaN differently + * @since 3.4 Changed signature from max(float[]) to max(float...) + */ + public static float max(final float... array) { + // Validates input + validateArray(array); + + // Finds and returns max + float max = array[0]; + for (int j = 1; j < array.length; j++) { + if (Float.isNaN(array[j])) { + return Float.NaN; + } + if (array[j] > max) { + max = array[j]; + } + } + + return max; + } + + /** + * Checks if the specified array is neither null nor empty. + * + * @param array the array to check + * @throws IllegalArgumentException if {@code array} is either {@code null} or empty + */ + private static void validateArray(final Object array) { + if (array == null) { + throw new IllegalArgumentException("The Array must not be null"); + } + Validate.isTrue(Array.getLength(array) != 0, "Array cannot be empty."); + } + + // 3 param min + //----------------------------------------------------------------------- + /** + *

Gets the minimum of three long values.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the smallest of the values + */ + public static long min(long a, final long b, final long c) { + if (b < a) { + a = b; + } + if (c < a) { + a = c; + } + return a; + } + + /** + *

Gets the minimum of three int values.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the smallest of the values + */ + public static int min(int a, final int b, final int c) { + if (b < a) { + a = b; + } + if (c < a) { + a = c; + } + return a; + } + + /** + *

Gets the minimum of three short values.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the smallest of the values + */ + public static short min(short a, final short b, final short c) { + if (b < a) { + a = b; + } + if (c < a) { + a = c; + } + return a; + } + + /** + *

Gets the minimum of three byte values.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the smallest of the values + */ + public static byte min(byte a, final byte b, final byte c) { + if (b < a) { + a = b; + } + if (c < a) { + a = c; + } + return a; + } + + /** + *

Gets the minimum of three double values.

+ * + *

If any value is NaN, NaN is + * returned. Infinity is handled.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the smallest of the values + * @see IEEE754rUtils#min(double, double, double) for a version of this method that handles NaN differently + */ + public static double min(final double a, final double b, final double c) { + return Math.min(Math.min(a, b), c); + } + + /** + *

Gets the minimum of three float values.

+ * + *

If any value is NaN, NaN is + * returned. Infinity is handled.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the smallest of the values + * @see IEEE754rUtils#min(float, float, float) for a version of this method that handles NaN differently + */ + public static float min(final float a, final float b, final float c) { + return Math.min(Math.min(a, b), c); + } + + // 3 param max + //----------------------------------------------------------------------- + /** + *

Gets the maximum of three long values.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the largest of the values + */ + public static long max(long a, final long b, final long c) { + if (b > a) { + a = b; + } + if (c > a) { + a = c; + } + return a; + } + + /** + *

Gets the maximum of three int values.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the largest of the values + */ + public static int max(int a, final int b, final int c) { + if (b > a) { + a = b; + } + if (c > a) { + a = c; + } + return a; + } + + /** + *

Gets the maximum of three short values.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the largest of the values + */ + public static short max(short a, final short b, final short c) { + if (b > a) { + a = b; + } + if (c > a) { + a = c; + } + return a; + } + + /** + *

Gets the maximum of three byte values.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the largest of the values + */ + public static byte max(byte a, final byte b, final byte c) { + if (b > a) { + a = b; + } + if (c > a) { + a = c; + } + return a; + } + + /** + *

Gets the maximum of three double values.

+ * + *

If any value is NaN, NaN is + * returned. Infinity is handled.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the largest of the values + * @see IEEE754rUtils#max(double, double, double) for a version of this method that handles NaN differently + */ + public static double max(final double a, final double b, final double c) { + return Math.max(Math.max(a, b), c); + } + + /** + *

Gets the maximum of three float values.

+ * + *

If any value is NaN, NaN is + * returned. Infinity is handled.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the largest of the values + * @see IEEE754rUtils#max(float, float, float) for a version of this method that handles NaN differently + */ + public static float max(final float a, final float b, final float c) { + return Math.max(Math.max(a, b), c); + } + + //----------------------------------------------------------------------- + /** + *

Checks whether the String contains only + * digit characters.

+ * + *

Null and empty String will return + * false.

+ * + * @param str the String to check + * @return true if str contains only Unicode numeric + */ + public static boolean isDigits(final String str) { + return StringUtils.isNumeric(str); + } + + /** + *

Checks whether the String a valid Java number.

+ * + *

Valid numbers include hexadecimal marked with the 0x or + * 0X qualifier, octal numbers, scientific notation and + * numbers marked with a type qualifier (e.g. 123L).

+ * + *

Non-hexadecimal strings beginning with a leading zero are + * treated as octal values. Thus the string 09 will return + * false, since 9 is not a valid octal value. + * However, numbers beginning with {@code 0.} are treated as decimal.

+ * + *

null and empty/blank {@code String} will return + * false.

+ * + *

Note, {@link #createNumber(String)} should return a number for every + * input resuling in true.

+ * + * @param str the String to check + * @return true if the string is a correctly formatted number + * @since 3.3 the code supports hex {@code 0Xhhh} an + * octal {@code 0ddd} validation + * @deprecated This feature will be removed in Lang 4.0, + * use {@link NumberUtils#isCreatable(String)} instead + */ + @Deprecated + public static boolean isNumber(final String str) { + return isCreatable(str); + } + + /** + *

Checks whether the String a valid Java number.

+ * + *

Valid numbers include hexadecimal marked with the 0x or + * 0X qualifier, octal numbers, scientific notation and + * numbers marked with a type qualifier (e.g. 123L).

+ * + *

Non-hexadecimal strings beginning with a leading zero are + * treated as octal values. Thus the string 09 will return + * false, since 9 is not a valid octal value. + * However, numbers beginning with {@code 0.} are treated as decimal.

+ * + *

null and empty/blank {@code String} will return + * false.

+ * + *

Note, {@link #createNumber(String)} should return a number for every + * input resuling in true.

+ * + * @param str the String to check + * @return true if the string is a correctly formatted number + * @since 3.5 the code supports the "+" suffix on numbers except for integers in Java 1.6 + */ + public static boolean isCreatable(final String str) { + if (StringUtils.isEmpty(str)) { + return false; + } + final char[] chars = str.toCharArray(); + int sz = chars.length; + boolean hasExp = false; + boolean hasDecPoint = false; + boolean allowSigns = false; + boolean foundDigit = false; + // deal with any possible sign up front + final int start = chars[0] == '-' || chars[0] == '+' ? 1 : 0; + final boolean hasLeadingPlusSign = start == 1 && chars[0] == '+'; + if (sz > start + 1 && chars[start] == '0') { // leading 0 + if (chars[start + 1] == 'x' || chars[start + 1] == 'X') { // leading 0x/0X + int i = start + 2; + if (i == sz) { + return false; // str == "0x" + } + // checking hex (it can't be anything else) + for (; i < chars.length; i++) { + if ((chars[i] < '0' || chars[i] > '9') + && (chars[i] < 'a' || chars[i] > 'f') + && (chars[i] < 'A' || chars[i] > 'F')) { + return false; + } + } + return true; + } else if (Character.isDigit(chars[start + 1])) { + // leading 0, but not hex, must be octal + int i = start + 1; + for (; i < chars.length; i++) { + if (chars[i] < '0' || chars[i] > '7') { + return false; + } + } + return true; + } + } + sz--; // don't want to loop to the last char, check it afterwords + // for type qualifiers + int i = start; + // loop to the next to last char or to the last char if we need another digit to + // make a valid number (e.g. chars[0..5] = "1234E") + while (i < sz || i < sz + 1 && allowSigns && !foundDigit) { + if (chars[i] >= '0' && chars[i] <= '9') { + foundDigit = true; + allowSigns = false; + + } else if (chars[i] == '.') { + if (hasDecPoint || hasExp) { + // two decimal points or dec in exponent + return false; + } + hasDecPoint = true; + } else if (chars[i] == 'e' || chars[i] == 'E') { + // we've already taken care of hex. + if (hasExp) { + // two E's + return false; + } + if (!foundDigit) { + return false; + } + hasExp = true; + allowSigns = true; + } else if (chars[i] == '+' || chars[i] == '-') { + if (!allowSigns) { + return false; + } + allowSigns = false; + foundDigit = false; // we need a digit after the E + } else { + return false; + } + i++; + } + if (i < chars.length) { + if (chars[i] >= '0' && chars[i] <= '9') { + if (SystemUtils.IS_JAVA_1_6 && hasLeadingPlusSign && !hasDecPoint) { + return false; + } + // no type qualifier, OK + return true; + } + if (chars[i] == 'e' || chars[i] == 'E') { + // can't have an E at the last byte + return false; + } + if (chars[i] == '.') { + if (hasDecPoint || hasExp) { + // two decimal points or dec in exponent + return false; + } + // single trailing decimal point after non-exponent is ok + return foundDigit; + } + if (!allowSigns + && (chars[i] == 'd' + || chars[i] == 'D' + || chars[i] == 'f' + || chars[i] == 'F')) { + return foundDigit; + } + if (chars[i] == 'l' + || chars[i] == 'L') { + // not allowing L with an exponent or decimal point + return foundDigit && !hasExp && !hasDecPoint; + } + // last character is illegal + return false; + } + // allowSigns is true iff the val ends in 'E' + // found digit it to make sure weird stuff like '.' and '1E-' doesn't pass + return !allowSigns && foundDigit; + } + + /** + *

Checks whether the given String is a parsable number.

+ * + *

Parsable numbers include those Strings understood by {@link Integer#parseInt(String)}, + * {@link Long#parseLong(String)}, {@link Float#parseFloat(String)} or + * {@link Double#parseDouble(String)}. This method can be used instead of catching {@link java.text.ParseException} + * when calling one of those methods.

+ * + *

Hexadecimal and scientific notations are not considered parsable. + * See {@link #isCreatable(String)} on those cases.

+ * + *

{@code Null} and empty String will return false.

+ * + * @param str the String to check. + * @return {@code true} if the string is a parsable number. + * @since 3.4 + */ + public static boolean isParsable(final String str) { + if (StringUtils.isEmpty(str)) { + return false; + } + if (str.charAt(str.length() - 1) == '.') { + return false; + } + if (str.charAt(0) == '-') { + if (str.length() == 1) { + return false; + } + return withDecimalsParsing(str, 1); + } else { + return withDecimalsParsing(str, 0); + } + } + + private static boolean withDecimalsParsing(final String str, final int beginIdx) { + int decimalPoints = 0; + for (int i = beginIdx; i < str.length(); i++) { + final boolean isDecimalPoint = str.charAt(i) == '.'; + if (isDecimalPoint) { + decimalPoints++; + } + if (decimalPoints > 1) { + return false; + } + if (!isDecimalPoint && !Character.isDigit(str.charAt(i))) { + return false; + } + } + return true; + } + + /** + *

Compares two {@code int} values numerically. This is the same functionality as provided in Java 7.

+ * + * @param x the first {@code int} to compare + * @param y the second {@code int} 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(int x, int y) { + if (x == y) { + return 0; + } + return x < y ? -1 : 1; + } + + /** + *

Compares to {@code long} values numerically. This is the same functionality as provided in Java 7.

+ * + * @param x the first {@code long} to compare + * @param y the second {@code long} 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(long x, long y) { + if (x == y) { + return 0; + } + return x < y ? -1 : 1; + } + + /** + *

Compares to {@code short} values numerically. This is the same functionality as provided in Java 7.

+ * + * @param x the first {@code short} to compare + * @param y the second {@code short} 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(short x, short y) { + if (x == y) { + return 0; + } + return x < y ? -1 : 1; + } + + /** + *

Compares two {@code byte} values numerically. This is the same functionality as provided in Java 7.

+ * + * @param x the first {@code byte} to compare + * @param y the second {@code byte} 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(byte x, byte y) { + return x - y; + } +} diff --git a/Java/commons-lang-NumberUtils_275/metadata.json b/Java/commons-lang-NumberUtils_275/metadata.json new file mode 100644 index 000000000..d284bc17f --- /dev/null +++ b/Java/commons-lang-NumberUtils_275/metadata.json @@ -0,0 +1,21 @@ +{ + "language": "java", + "id": "commons-lang-NumberUtils_275", + "buggyPath": ".", + "referencePath": null, + "buildCommand": "mvn package -V -B -Denforcer.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true -Drat.skip=true -Dlicense.skip=true -Dfindbugs.skip=true -Dgpg.skip=true -Dskip.npm=true -Dskip.gulp=true -Dskip.bower=true -Drat.numUnapprovedLicenses=100 -DskipTests=true -DskipITs=true -Dtest=None -DfailIfNoTests=false", + "testCommand": "mvn test -V -B -Denforcer.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true -Drat.skip=true -Dlicense.skip=true -Dfindbugs.skip=true -Dgpg.skip=true -Dskip.npm=true -Dskip.gulp=true -Dskip.bower=true -Drat.numUnapprovedLicenses=100", + "categories": [ + "safety", + "npe" + ], + "npe": { + "filepath": "src/main/java/org/apache/commons/lang3/math/NumberUtils.java", + "line": 299, + "npe_method": "toDouble", + "deref_field": "str", + "npe_class": "NumberUtils", + "repo": "commons-lang", + "bug_id": "NumberUtils_275" + } +} diff --git a/Java/commons-lang-NumberUtils_275/npe.json b/Java/commons-lang-NumberUtils_275/npe.json new file mode 100644 index 000000000..fd9402686 --- /dev/null +++ b/Java/commons-lang-NumberUtils_275/npe.json @@ -0,0 +1,7 @@ +{ + "filepath": "src/main/java/org/apache/commons/lang3/math/NumberUtils.java", + "line": 299, + "npe_method": "toDouble", + "deref_field": "str", + "npe_class": "NumberUtils" +} \ No newline at end of file diff --git a/Java/commons-lang-NumberUtils_452/Dockerfile b/Java/commons-lang-NumberUtils_452/Dockerfile new file mode 100644 index 000000000..7b7fbe349 --- /dev/null +++ b/Java/commons-lang-NumberUtils_452/Dockerfile @@ -0,0 +1,18 @@ +FROM ghcr.io/kupl/starlab-benchmarks/java-base:commons-lang + +ENV TZ=Asia/Seoul + +COPY ./metadata.json . +COPY ./npe.json . +COPY ./buggy.java /tmp/buggy.java +RUN export BUGGY_PATH=$(cat metadata.json | jq -r ".npe.filepath") \ + && export BUGGY_LINE=$(cat metadata.json | jq -r ".npe.line") \ + && export BUGGY_MTHD=$(cat metadata.json | jq -r ".npe.npe_method") \ + && mv /tmp/buggy.java $BUGGY_PATH \ + && echo "[{\"filepath\": \"$BUGGY_PATH\", \"line\": $BUGGY_LINE, \"method_name\": \"$BUGGY_MTHD\"}]" | jq . > traces.json + +RUN git init . && git add -A + +RUN $(cat metadata.json | jq -r ".buildCommand") + +RUN $(cat metadata.json | jq -r ".testCommand"); if [ $? -eq 0 ]; then exit 1; fi diff --git a/Java/commons-lang-NumberUtils_452/buggy.java b/Java/commons-lang-NumberUtils_452/buggy.java new file mode 100644 index 000000000..cb535e1e9 --- /dev/null +++ b/Java/commons-lang-NumberUtils_452/buggy.java @@ -0,0 +1,1710 @@ +/* + * 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 java.lang.reflect.Array; +import java.math.BigDecimal; +import java.math.BigInteger; + +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.SystemUtils; +import org.apache.commons.lang3.Validate; + +/** + *

Provides extra functionality for Java Number classes.

+ * + * @since 2.0 + */ +public class NumberUtils { + + /** Reusable Long constant for zero. */ + public static final Long LONG_ZERO = Long.valueOf(0L); + /** Reusable Long constant for one. */ + public static final Long LONG_ONE = Long.valueOf(1L); + /** Reusable Long constant for minus one. */ + public static final Long LONG_MINUS_ONE = Long.valueOf(-1L); + /** Reusable Integer constant for zero. */ + public static final Integer INTEGER_ZERO = Integer.valueOf(0); + /** Reusable Integer constant for one. */ + public static final Integer INTEGER_ONE = Integer.valueOf(1); + /** Reusable Integer constant for minus one. */ + public static final Integer INTEGER_MINUS_ONE = Integer.valueOf(-1); + /** Reusable Short constant for zero. */ + public static final Short SHORT_ZERO = Short.valueOf((short) 0); + /** Reusable Short constant for one. */ + public static final Short SHORT_ONE = Short.valueOf((short) 1); + /** Reusable Short constant for minus one. */ + public static final Short SHORT_MINUS_ONE = Short.valueOf((short) -1); + /** Reusable Byte constant for zero. */ + public static final Byte BYTE_ZERO = Byte.valueOf((byte) 0); + /** Reusable Byte constant for one. */ + public static final Byte BYTE_ONE = Byte.valueOf((byte) 1); + /** Reusable Byte constant for minus one. */ + public static final Byte BYTE_MINUS_ONE = Byte.valueOf((byte) -1); + /** Reusable Double constant for zero. */ + public static final Double DOUBLE_ZERO = Double.valueOf(0.0d); + /** Reusable Double constant for one. */ + public static final Double DOUBLE_ONE = Double.valueOf(1.0d); + /** Reusable Double constant for minus one. */ + public static final Double DOUBLE_MINUS_ONE = Double.valueOf(-1.0d); + /** Reusable Float constant for zero. */ + public static final Float FLOAT_ZERO = Float.valueOf(0.0f); + /** Reusable Float constant for one. */ + public static final Float FLOAT_ONE = Float.valueOf(1.0f); + /** Reusable Float constant for minus one. */ + public static final Float FLOAT_MINUS_ONE = Float.valueOf(-1.0f); + + /** + *

NumberUtils instances should NOT be constructed in standard programming. + * Instead, the class should be used as NumberUtils.toInt("6");.

+ * + *

This constructor is public to permit tools that require a JavaBean instance + * to operate.

+ */ + public NumberUtils() { + super(); + } + + //----------------------------------------------------------------------- + /** + *

Convert a String to an int, returning + * zero if the conversion fails.

+ * + *

If the string is null, zero is returned.

+ * + *
+     *   NumberUtils.toInt(null) = 0
+     *   NumberUtils.toInt("")   = 0
+     *   NumberUtils.toInt("1")  = 1
+     * 
+ * + * @param str the string to convert, may be null + * @return the int represented by the string, or zero if + * conversion fails + * @since 2.1 + */ + public static int toInt(final String str) { + return toInt(str, 0); + } + + /** + *

Convert a String to an int, returning a + * default value if the conversion fails.

+ * + *

If the string is null, the default value is returned.

+ * + *
+     *   NumberUtils.toInt(null, 1) = 1
+     *   NumberUtils.toInt("", 1)   = 1
+     *   NumberUtils.toInt("1", 0)  = 1
+     * 
+ * + * @param str the string to convert, may be null + * @param defaultValue the default value + * @return the int represented by the string, or the default if conversion fails + * @since 2.1 + */ + public static int toInt(final String str, final int defaultValue) { + if(str == null) { + return defaultValue; + } + try { + return Integer.parseInt(str); + } catch (final NumberFormatException nfe) { + return defaultValue; + } + } + + /** + *

Convert a String to a long, returning + * zero if the conversion fails.

+ * + *

If the string is null, zero is returned.

+ * + *
+     *   NumberUtils.toLong(null) = 0L
+     *   NumberUtils.toLong("")   = 0L
+     *   NumberUtils.toLong("1")  = 1L
+     * 
+ * + * @param str the string to convert, may be null + * @return the long represented by the string, or 0 if + * conversion fails + * @since 2.1 + */ + public static long toLong(final String str) { + return toLong(str, 0L); + } + + /** + *

Convert a String to a long, returning a + * default value if the conversion fails.

+ * + *

If the string is null, the default value is returned.

+ * + *
+     *   NumberUtils.toLong(null, 1L) = 1L
+     *   NumberUtils.toLong("", 1L)   = 1L
+     *   NumberUtils.toLong("1", 0L)  = 1L
+     * 
+ * + * @param str the string to convert, may be null + * @param defaultValue the default value + * @return the long represented by the string, or the default if conversion fails + * @since 2.1 + */ + public static long toLong(final String str, final long defaultValue) { + if (str == null) { + return defaultValue; + } + try { + return Long.parseLong(str); + } catch (final NumberFormatException nfe) { + return defaultValue; + } + } + + /** + *

Convert a String to a float, returning + * 0.0f if the conversion fails.

+ * + *

If the string str is null, + * 0.0f is returned.

+ * + *
+     *   NumberUtils.toFloat(null)   = 0.0f
+     *   NumberUtils.toFloat("")     = 0.0f
+     *   NumberUtils.toFloat("1.5")  = 1.5f
+     * 
+ * + * @param str the string to convert, may be null + * @return the float represented by the string, or 0.0f + * if conversion fails + * @since 2.1 + */ + public static float toFloat(final String str) { + return toFloat(str, 0.0f); + } + + /** + *

Convert a String to a float, returning a + * default value if the conversion fails.

+ * + *

If the string str is null, the default + * value is returned.

+ * + *
+     *   NumberUtils.toFloat(null, 1.1f)   = 1.0f
+     *   NumberUtils.toFloat("", 1.1f)     = 1.1f
+     *   NumberUtils.toFloat("1.5", 0.0f)  = 1.5f
+     * 
+ * + * @param str the string to convert, may be null + * @param defaultValue the default value + * @return the float represented by the string, or defaultValue + * if conversion fails + * @since 2.1 + */ + public static float toFloat(final String str, final float defaultValue) { + if (str == null) { + return defaultValue; + } + try { + return Float.parseFloat(str); + } catch (final NumberFormatException nfe) { + return defaultValue; + } + } + + /** + *

Convert a String to a double, returning + * 0.0d if the conversion fails.

+ * + *

If the string str is null, + * 0.0d is returned.

+ * + *
+     *   NumberUtils.toDouble(null)   = 0.0d
+     *   NumberUtils.toDouble("")     = 0.0d
+     *   NumberUtils.toDouble("1.5")  = 1.5d
+     * 
+ * + * @param str the string to convert, may be null + * @return the double represented by the string, or 0.0d + * if conversion fails + * @since 2.1 + */ + public static double toDouble(final String str) { + return toDouble(str, 0.0d); + } + + /** + *

Convert a String to a double, returning a + * default value if the conversion fails.

+ * + *

If the string str is null, the default + * value is returned.

+ * + *
+     *   NumberUtils.toDouble(null, 1.1d)   = 1.1d
+     *   NumberUtils.toDouble("", 1.1d)     = 1.1d
+     *   NumberUtils.toDouble("1.5", 0.0d)  = 1.5d
+     * 
+ * + * @param str the string to convert, may be null + * @param defaultValue the default value + * @return the double represented by the string, or defaultValue + * if conversion fails + * @since 2.1 + */ + public static double toDouble(final String str, final double defaultValue) { + if (str == null) { + return defaultValue; + } + try { + return Double.parseDouble(str); + } catch (final NumberFormatException nfe) { + return defaultValue; + } + } + + //----------------------------------------------------------------------- + /** + *

Convert a String to a byte, returning + * zero if the conversion fails.

+ * + *

If the string is null, zero is returned.

+ * + *
+     *   NumberUtils.toByte(null) = 0
+     *   NumberUtils.toByte("")   = 0
+     *   NumberUtils.toByte("1")  = 1
+     * 
+ * + * @param str the string to convert, may be null + * @return the byte represented by the string, or zero if + * conversion fails + * @since 2.5 + */ + public static byte toByte(final String str) { + return toByte(str, (byte) 0); + } + + /** + *

Convert a String to a byte, returning a + * default value if the conversion fails.

+ * + *

If the string is null, the default value is returned.

+ * + *
+     *   NumberUtils.toByte(null, 1) = 1
+     *   NumberUtils.toByte("", 1)   = 1
+     *   NumberUtils.toByte("1", 0)  = 1
+     * 
+ * + * @param str the string to convert, may be null + * @param defaultValue the default value + * @return the byte represented by the string, or the default if conversion fails + * @since 2.5 + */ + public static byte toByte(final String str, final byte defaultValue) { + if(str == null) { + return defaultValue; + } + try { + return Byte.parseByte(str); + } catch (final NumberFormatException nfe) { + return defaultValue; + } + } + + /** + *

Convert a String to a short, returning + * zero if the conversion fails.

+ * + *

If the string is null, zero is returned.

+ * + *
+     *   NumberUtils.toShort(null) = 0
+     *   NumberUtils.toShort("")   = 0
+     *   NumberUtils.toShort("1")  = 1
+     * 
+ * + * @param str the string to convert, may be null + * @return the short represented by the string, or zero if + * conversion fails + * @since 2.5 + */ + public static short toShort(final String str) { + return toShort(str, (short) 0); + } + + /** + *

Convert a String to an short, returning a + * default value if the conversion fails.

+ * + *

If the string is null, the default value is returned.

+ * + *
+     *   NumberUtils.toShort(null, 1) = 1
+     *   NumberUtils.toShort("", 1)   = 1
+     *   NumberUtils.toShort("1", 0)  = 1
+     * 
+ * + * @param str the string to convert, may be null + * @param defaultValue the default value + * @return the short represented by the string, or the default if conversion fails + * @since 2.5 + */ + public static short toShort(final String str, final short defaultValue) { + if(str == null) { + return defaultValue; + } + try { + return Short.parseShort(str); + } catch (final NumberFormatException nfe) { + return defaultValue; + } + } + + //----------------------------------------------------------------------- + // must handle Long, Float, Integer, Float, Short, + // BigDecimal, BigInteger and Byte + // useful methods: + // Byte.decode(String) + // Byte.valueOf(String,int radix) + // Byte.valueOf(String) + // Double.valueOf(String) + // Float.valueOf(String) + // Float.valueOf(String) + // Integer.valueOf(String,int radix) + // Integer.valueOf(String) + // Integer.decode(String) + // Integer.getInteger(String) + // Integer.getInteger(String,int val) + // Integer.getInteger(String,Integer val) + // Integer.valueOf(String) + // Double.valueOf(String) + // new Byte(String) + // Long.valueOf(String) + // Long.getLong(String) + // Long.getLong(String,int) + // Long.getLong(String,Integer) + // Long.valueOf(String,int) + // Long.valueOf(String) + // Short.valueOf(String) + // Short.decode(String) + // Short.valueOf(String,int) + // Short.valueOf(String) + // new BigDecimal(String) + // new BigInteger(String) + // new BigInteger(String,int radix) + // Possible inputs: + // 45 45.5 45E7 4.5E7 Hex Oct Binary xxxF xxxD xxxf xxxd + // plus minus everything. Prolly more. A lot are not separable. + + /** + *

Turns a string value into a java.lang.Number.

+ * + *

If the string starts with {@code 0x} or {@code -0x} (lower or upper case) or {@code #} or {@code -#}, it + * will be interpreted as a hexadecimal Integer - or Long, if the number of digits after the + * prefix is more than 8 - or BigInteger if there are more than 16 digits. + *

+ *

Then, the value is examined for a type qualifier on the end, i.e. one of + * 'f','F','d','D','l','L'. If it is found, it starts + * trying to create successively larger types from the type specified + * until one is found that can represent the value.

+ * + *

If a type specifier is not found, it will check for a decimal point + * and then try successively larger types from Integer to + * BigInteger and from Float to + * BigDecimal.

+ * + *

+ * Integral values with a leading {@code 0} will be interpreted as octal; the returned number will + * be Integer, Long or BigDecimal as appropriate. + *

+ * + *

Returns null if the string is null.

+ * + *

This method does not trim the input string, i.e., strings with leading + * or trailing spaces will generate NumberFormatExceptions.

+ * + * @param str String containing a number, may be null + * @return Number created from the string (or null if the input is null) + * @throws NumberFormatException if the value cannot be converted + */ +// ----------------------------------------------------------------------- +// must handle Long, Float, Integer, Float, Short, +// BigDecimal, BigInteger and Byte +// useful methods: +// Byte.decode(String) +// Byte.valueOf(String,int radix) +// Byte.valueOf(String) +// Double.valueOf(String) +// Float.valueOf(String) +// Float.valueOf(String) +// Integer.valueOf(String,int radix) +// Integer.valueOf(String) +// Integer.decode(String) +// Integer.getInteger(String) +// Integer.getInteger(String,int val) +// Integer.getInteger(String,Integer val) +// Integer.valueOf(String) +// Double.valueOf(String) +// new Byte(String) +// Long.valueOf(String) +// Long.getLong(String) +// Long.getLong(String,int) +// Long.getLong(String,Integer) +// Long.valueOf(String,int) +// Long.valueOf(String) +// Short.valueOf(String) +// Short.decode(String) +// Short.valueOf(String,int) +// Short.valueOf(String) +// new BigDecimal(String) +// new BigInteger(String) +// new BigInteger(String,int radix) +// Possible inputs: +// 45 45.5 45E7 4.5E7 Hex Oct Binary xxxF xxxD xxxf xxxd +// plus minus everything. Prolly more. A lot are not separable. +/** + *

Turns a string value into a java.lang.Number.

+ * + *

If the string starts with {@code 0x} or {@code -0x} (lower or upper case) or {@code #} or {@code -#}, it + * will be interpreted as a hexadecimal Integer - or Long, if the number of digits after the + * prefix is more than 8 - or BigInteger if there are more than 16 digits. + *

+ *

Then, the value is examined for a type qualifier on the end, i.e. one of + * 'f','F','d','D','l','L'. If it is found, it starts + * trying to create successively larger types from the type specified + * until one is found that can represent the value.

+ * + *

If a type specifier is not found, it will check for a decimal point + * and then try successively larger types from Integer to + * BigInteger and from Float to + * BigDecimal.

+ * + *

+ * Integral values with a leading {@code 0} will be interpreted as octal; the returned number will + * be Integer, Long or BigDecimal as appropriate. + *

+ * + *

Returns null if the string is null.

+ * + *

This method does not trim the input string, i.e., strings with leading + * or trailing spaces will generate NumberFormatExceptions.

+ * + * @param str + * String containing a number, may be null + * @return Number created from the string (or null if the input is null) + * @throws NumberFormatException + * if the value cannot be converted + */ +public static java.lang.Number createNumber(final java.lang.String str) throws java.lang.NumberFormatException { + { + if (org.apache.commons.lang3.StringUtils.isBlank(/* NPEX_NULL_EXP */ + str)) { + throw new java.lang.NumberFormatException("A blank string is not a valid number"); + } + // Need to deal with all possible hex prefixes here + final java.lang.String[] hex_prefixes = new java.lang.String[]{ "0x", "0X", "-0x", "-0X", "#", "-#" }; + int pfxLen = 0; + for (final java.lang.String pfx : hex_prefixes) { + if (str.startsWith(pfx)) { + pfxLen += pfx.length(); + break; + } + } + if (pfxLen > 0) { + // we have a hex number + char firstSigDigit = 0;// strip leading zeroes + + for (int i = pfxLen; i < str.length(); i++) { + firstSigDigit = str.charAt(i); + if (firstSigDigit == '0') { + // count leading zeroes + pfxLen++; + } else { + break; + } + } + final int hexDigits = str.length() - pfxLen; + if ((hexDigits > 16) || ((hexDigits == 16) && (firstSigDigit > '7'))) { + // too many for Long + return org.apache.commons.lang3.math.NumberUtils.createBigInteger(str); + } + if ((hexDigits > 8) || ((hexDigits == 8) && (firstSigDigit > '7'))) { + // too many for an int + return org.apache.commons.lang3.math.NumberUtils.createLong(str); + } + return org.apache.commons.lang3.math.NumberUtils.createInteger(str); + } + final char lastChar = str.charAt(str.length() - 1); + java.lang.String mant; + java.lang.String dec; + java.lang.String exp; + final int decPos = str.indexOf('.'); + final int expPos = (str.indexOf('e') + str.indexOf('E')) + 1;// assumes both not present + + // if both e and E are present, this is caught by the checks on expPos (which prevent IOOBE) + // and the parsing which will detect if e or E appear in a number due to using the wrong offset + if (decPos > (-1)) { + // there is a decimal point + if (expPos > (-1)) { + // there is an exponent + if ((expPos < decPos) || (expPos > str.length())) { + // prevents double exponent causing IOOBE + throw new java.lang.NumberFormatException(str + " is not a valid number."); + } + dec = str.substring(decPos + 1, expPos); + } else { + dec = str.substring(decPos + 1); + } + mant = org.apache.commons.lang3.math.NumberUtils.getMantissa(str, decPos); + } else { + if (expPos > (-1)) { + if (expPos > str.length()) { + // prevents double exponent causing IOOBE + throw new java.lang.NumberFormatException(str + " is not a valid number."); + } + mant = org.apache.commons.lang3.math.NumberUtils.getMantissa(str, expPos); + } else { + mant = org.apache.commons.lang3.math.NumberUtils.getMantissa(str); + } + dec = null; + } + if ((!java.lang.Character.isDigit(lastChar)) && (lastChar != '.')) { + if ((expPos > (-1)) && (expPos < (str.length() - 1))) { + exp = str.substring(expPos + 1, str.length() - 1); + } else { + exp = null; + } + // Requesting a specific type.. + final java.lang.String numeric = str.substring(0, str.length() - 1); + final boolean allZeros = org.apache.commons.lang3.math.NumberUtils.isAllZeros(mant) && org.apache.commons.lang3.math.NumberUtils.isAllZeros(exp); + switch (lastChar) { + case 'l' : + case 'L' : + if (((dec == null) && (exp == null)) && (((numeric.charAt(0) == '-') && org.apache.commons.lang3.math.NumberUtils.isDigits(numeric.substring(1))) || org.apache.commons.lang3.math.NumberUtils.isDigits(numeric))) { + try { + return org.apache.commons.lang3.math.NumberUtils.createLong(numeric); + } catch (final java.lang.NumberFormatException nfe) { + // NOPMD + // Too big for a long + } + return org.apache.commons.lang3.math.NumberUtils.createBigInteger(numeric); + } + throw new java.lang.NumberFormatException(str + " is not a valid number."); + case 'f' : + case 'F' : + try { + final java.lang.Float f = org.apache.commons.lang3.math.NumberUtils.createFloat(str); + if (!(f.isInfinite() || ((f.floatValue() == 0.0F) && (!allZeros)))) { + // If it's too big for a float or the float value = 0 and the string + // has non-zeros in it, then float does not have the precision we want + return f; + } + } catch (final java.lang.NumberFormatException nfe) { + // NOPMD + // ignore the bad number + } + // $FALL-THROUGH$ + case 'd' : + case 'D' : + try { + final java.lang.Double d = org.apache.commons.lang3.math.NumberUtils.createDouble(str); + if (!(d.isInfinite() || ((d.floatValue() == 0.0) && (!allZeros)))) { + return d; + } + } catch (final java.lang.NumberFormatException nfe) { + // NOPMD + // ignore the bad number + } + try { + return org.apache.commons.lang3.math.NumberUtils.createBigDecimal(numeric); + } catch (final java.lang.NumberFormatException e) { + // NOPMD + // ignore the bad number + } + // $FALL-THROUGH$ + default : + throw new java.lang.NumberFormatException(str + " is not a valid number."); + } + } + // User doesn't have a preference on the return type, so let's start + // small and go from there... + if ((expPos > (-1)) && (expPos < (str.length() - 1))) { + exp = str.substring(expPos + 1, str.length()); + } else { + exp = null; + } + if ((dec == null) && (exp == null)) { + // no decimal point and no exponent + // Must be an Integer, Long, Biginteger + try { + return org.apache.commons.lang3.math.NumberUtils.createInteger(str); + } catch (final java.lang.NumberFormatException nfe) { + // NOPMD + // ignore the bad number + } + try { + return org.apache.commons.lang3.math.NumberUtils.createLong(str); + } catch (final java.lang.NumberFormatException nfe) { + // NOPMD + // ignore the bad number + } + return org.apache.commons.lang3.math.NumberUtils.createBigInteger(str); + } + // Must be a Float, Double, BigDecimal + final boolean allZeros = org.apache.commons.lang3.math.NumberUtils.isAllZeros(mant) && org.apache.commons.lang3.math.NumberUtils.isAllZeros(exp); + try { + final java.lang.Float f = org.apache.commons.lang3.math.NumberUtils.createFloat(str); + final java.lang.Double d = org.apache.commons.lang3.math.NumberUtils.createDouble(str); + if (((!f.isInfinite()) && (!((f.floatValue() == 0.0F) && (!allZeros)))) && f.toString().equals(d.toString())) { + return f; + } + if ((!d.isInfinite()) && (!((d.doubleValue() == 0.0) && (!allZeros)))) { + final java.math.BigDecimal b = org.apache.commons.lang3.math.NumberUtils.createBigDecimal(str); + if (b.compareTo(java.math.BigDecimal.valueOf(d)) == 0) { + return d; + } + return b; + } + } catch (final java.lang.NumberFormatException nfe) { + // NOPMD + // ignore the bad number + } + return org.apache.commons.lang3.math.NumberUtils.createBigDecimal(str); + } +} + + /** + *

Utility method for {@link #createNumber(java.lang.String)}.

+ * + *

Returns mantissa of the given number.

+ * + * @param str the string representation of the number + * @return mantissa of the given number + */ + private static String getMantissa(final String str) { + return getMantissa(str, str.length()); + } + + /** + *

Utility method for {@link #createNumber(java.lang.String)}.

+ * + *

Returns mantissa of the given number.

+ * + * @param str the string representation of the number + * @param stopPos the position of the exponent or decimal point + * @return mantissa of the given number + */ + private static String getMantissa(final String str, final int stopPos) { + final char firstChar = str.charAt(0); + final boolean hasSign = firstChar == '-' || firstChar == '+'; + + return hasSign ? str.substring(1, stopPos) : str.substring(0, stopPos); + } + + /** + *

Utility method for {@link #createNumber(java.lang.String)}.

+ * + *

Returns true if s is null.

+ * + * @param str the String to check + * @return if it is all zeros or null + */ + private static boolean isAllZeros(final String str) { + if (str == null) { + return true; + } + for (int i = str.length() - 1; i >= 0; i--) { + if (str.charAt(i) != '0') { + return false; + } + } + return str.length() > 0; + } + + //----------------------------------------------------------------------- + /** + *

Convert a String to a Float.

+ * + *

Returns null if the string is null.

+ * + * @param str a String to convert, may be null + * @return converted Float (or null if the input is null) + * @throws NumberFormatException if the value cannot be converted + */ + public static Float createFloat(final String str) { + if (str == null) { + return null; + } + return Float.valueOf(str); + } + + /** + *

Convert a String to a Double.

+ * + *

Returns null if the string is null.

+ * + * @param str a String to convert, may be null + * @return converted Double (or null if the input is null) + * @throws NumberFormatException if the value cannot be converted + */ + public static Double createDouble(final String str) { + if (str == null) { + return null; + } + return Double.valueOf(str); + } + + /** + *

Convert a String to a Integer, handling + * hex (0xhhhh) and octal (0dddd) notations. + * N.B. a leading zero means octal; spaces are not trimmed.

+ * + *

Returns null if the string is null.

+ * + * @param str a String to convert, may be null + * @return converted Integer (or null if the input is null) + * @throws NumberFormatException if the value cannot be converted + */ + public static Integer createInteger(final String str) { + if (str == null) { + return null; + } + // decode() handles 0xAABD and 0777 (hex and octal) as well. + return Integer.decode(str); + } + + /** + *

Convert a String to a Long; + * since 3.1 it handles hex (0Xhhhh) and octal (0ddd) notations. + * N.B. a leading zero means octal; spaces are not trimmed.

+ * + *

Returns null if the string is null.

+ * + * @param str a String to convert, may be null + * @return converted Long (or null if the input is null) + * @throws NumberFormatException if the value cannot be converted + */ + public static Long createLong(final String str) { + if (str == null) { + return null; + } + return Long.decode(str); + } + + /** + *

Convert a String to a BigInteger; + * since 3.2 it handles hex (0x or #) and octal (0) notations.

+ * + *

Returns null if the string is null.

+ * + * @param str a String to convert, may be null + * @return converted BigInteger (or null if the input is null) + * @throws NumberFormatException if the value cannot be converted + */ + public static BigInteger createBigInteger(final String str) { + if (str == null) { + return null; + } + int pos = 0; // offset within string + int radix = 10; + boolean negate = false; // need to negate later? + if (str.startsWith("-")) { + negate = true; + pos = 1; + } + if (str.startsWith("0x", pos) || str.startsWith("0X", pos)) { // hex + radix = 16; + pos += 2; + } else if (str.startsWith("#", pos)) { // alternative hex (allowed by Long/Integer) + radix = 16; + pos ++; + } else if (str.startsWith("0", pos) && str.length() > pos + 1) { // octal; so long as there are additional digits + radix = 8; + pos ++; + } // default is to treat as decimal + + final BigInteger value = new BigInteger(str.substring(pos), radix); + return negate ? value.negate() : value; + } + + /** + *

Convert a String to a BigDecimal.

+ * + *

Returns null if the string is null.

+ * + * @param str a String to convert, may be null + * @return converted BigDecimal (or null if the input is null) + * @throws NumberFormatException if the value cannot be converted + */ + public static BigDecimal createBigDecimal(final String str) { + if (str == null) { + return null; + } + // handle JDK1.3.1 bug where "" throws IndexOutOfBoundsException + if (StringUtils.isBlank(str)) { + throw new NumberFormatException("A blank string is not a valid number"); + } + if (str.trim().startsWith("--")) { + // this is protection for poorness in java.lang.BigDecimal. + // it accepts this as a legal value, but it does not appear + // to be in specification of class. OS X Java parses it to + // a wrong value. + throw new NumberFormatException(str + " is not a valid number."); + } + return new BigDecimal(str); + } + + // Min in array + //-------------------------------------------------------------------- + /** + *

Returns the minimum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the minimum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @since 3.4 Changed signature from min(long[]) to min(long...) + */ + public static long min(final long... array) { + // Validates input + validateArray(array); + + // Finds and returns min + long min = array[0]; + for (int i = 1; i < array.length; i++) { + if (array[i] < min) { + min = array[i]; + } + } + + return min; + } + + /** + *

Returns the minimum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the minimum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @since 3.4 Changed signature from min(int[]) to min(int...) + */ + public static int min(final int... array) { + // Validates input + validateArray(array); + + // Finds and returns min + int min = array[0]; + for (int j = 1; j < array.length; j++) { + if (array[j] < min) { + min = array[j]; + } + } + + return min; + } + + /** + *

Returns the minimum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the minimum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @since 3.4 Changed signature from min(short[]) to min(short...) + */ + public static short min(final short... array) { + // Validates input + validateArray(array); + + // Finds and returns min + short min = array[0]; + for (int i = 1; i < array.length; i++) { + if (array[i] < min) { + min = array[i]; + } + } + + return min; + } + + /** + *

Returns the minimum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the minimum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @since 3.4 Changed signature from min(byte[]) to min(byte...) + */ + public static byte min(final byte... array) { + // Validates input + validateArray(array); + + // Finds and returns min + byte min = array[0]; + for (int i = 1; i < array.length; i++) { + if (array[i] < min) { + min = array[i]; + } + } + + return min; + } + + /** + *

Returns the minimum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the minimum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @see IEEE754rUtils#min(double[]) IEEE754rUtils for a version of this method that handles NaN differently + * @since 3.4 Changed signature from min(double[]) to min(double...) + */ + public static double min(final double... array) { + // Validates input + validateArray(array); + + // Finds and returns min + double min = array[0]; + for (int i = 1; i < array.length; i++) { + if (Double.isNaN(array[i])) { + return Double.NaN; + } + if (array[i] < min) { + min = array[i]; + } + } + + return min; + } + + /** + *

Returns the minimum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the minimum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @see IEEE754rUtils#min(float[]) IEEE754rUtils for a version of this method that handles NaN differently + * @since 3.4 Changed signature from min(float[]) to min(float...) + */ + public static float min(final float... array) { + // Validates input + validateArray(array); + + // Finds and returns min + float min = array[0]; + for (int i = 1; i < array.length; i++) { + if (Float.isNaN(array[i])) { + return Float.NaN; + } + if (array[i] < min) { + min = array[i]; + } + } + + return min; + } + + // Max in array + //-------------------------------------------------------------------- + /** + *

Returns the maximum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the maximum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @since 3.4 Changed signature from max(long[]) to max(long...) + */ + public static long max(final long... array) { + // Validates input + validateArray(array); + + // Finds and returns max + long max = array[0]; + for (int j = 1; j < array.length; j++) { + if (array[j] > max) { + max = array[j]; + } + } + + return max; + } + + /** + *

Returns the maximum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the maximum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @since 3.4 Changed signature from max(int[]) to max(int...) + */ + public static int max(final int... array) { + // Validates input + validateArray(array); + + // Finds and returns max + int max = array[0]; + for (int j = 1; j < array.length; j++) { + if (array[j] > max) { + max = array[j]; + } + } + + return max; + } + + /** + *

Returns the maximum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the maximum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @since 3.4 Changed signature from max(short[]) to max(short...) + */ + public static short max(final short... array) { + // Validates input + validateArray(array); + + // Finds and returns max + short max = array[0]; + for (int i = 1; i < array.length; i++) { + if (array[i] > max) { + max = array[i]; + } + } + + return max; + } + + /** + *

Returns the maximum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the maximum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @since 3.4 Changed signature from max(byte[]) to max(byte...) + */ + public static byte max(final byte... array) { + // Validates input + validateArray(array); + + // Finds and returns max + byte max = array[0]; + for (int i = 1; i < array.length; i++) { + if (array[i] > max) { + max = array[i]; + } + } + + return max; + } + + /** + *

Returns the maximum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the maximum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @see IEEE754rUtils#max(double[]) IEEE754rUtils for a version of this method that handles NaN differently + * @since 3.4 Changed signature from max(double[]) to max(double...) + */ + public static double max(final double... array) { + // Validates input + validateArray(array); + + // Finds and returns max + double max = array[0]; + for (int j = 1; j < array.length; j++) { + if (Double.isNaN(array[j])) { + return Double.NaN; + } + if (array[j] > max) { + max = array[j]; + } + } + + return max; + } + + /** + *

Returns the maximum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the maximum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @see IEEE754rUtils#max(float[]) IEEE754rUtils for a version of this method that handles NaN differently + * @since 3.4 Changed signature from max(float[]) to max(float...) + */ + public static float max(final float... array) { + // Validates input + validateArray(array); + + // Finds and returns max + float max = array[0]; + for (int j = 1; j < array.length; j++) { + if (Float.isNaN(array[j])) { + return Float.NaN; + } + if (array[j] > max) { + max = array[j]; + } + } + + return max; + } + + /** + * Checks if the specified array is neither null nor empty. + * + * @param array the array to check + * @throws IllegalArgumentException if {@code array} is either {@code null} or empty + */ + private static void validateArray(final Object array) { + if (array == null) { + throw new IllegalArgumentException("The Array must not be null"); + } + Validate.isTrue(Array.getLength(array) != 0, "Array cannot be empty."); + } + + // 3 param min + //----------------------------------------------------------------------- + /** + *

Gets the minimum of three long values.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the smallest of the values + */ + public static long min(long a, final long b, final long c) { + if (b < a) { + a = b; + } + if (c < a) { + a = c; + } + return a; + } + + /** + *

Gets the minimum of three int values.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the smallest of the values + */ + public static int min(int a, final int b, final int c) { + if (b < a) { + a = b; + } + if (c < a) { + a = c; + } + return a; + } + + /** + *

Gets the minimum of three short values.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the smallest of the values + */ + public static short min(short a, final short b, final short c) { + if (b < a) { + a = b; + } + if (c < a) { + a = c; + } + return a; + } + + /** + *

Gets the minimum of three byte values.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the smallest of the values + */ + public static byte min(byte a, final byte b, final byte c) { + if (b < a) { + a = b; + } + if (c < a) { + a = c; + } + return a; + } + + /** + *

Gets the minimum of three double values.

+ * + *

If any value is NaN, NaN is + * returned. Infinity is handled.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the smallest of the values + * @see IEEE754rUtils#min(double, double, double) for a version of this method that handles NaN differently + */ + public static double min(final double a, final double b, final double c) { + return Math.min(Math.min(a, b), c); + } + + /** + *

Gets the minimum of three float values.

+ * + *

If any value is NaN, NaN is + * returned. Infinity is handled.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the smallest of the values + * @see IEEE754rUtils#min(float, float, float) for a version of this method that handles NaN differently + */ + public static float min(final float a, final float b, final float c) { + return Math.min(Math.min(a, b), c); + } + + // 3 param max + //----------------------------------------------------------------------- + /** + *

Gets the maximum of three long values.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the largest of the values + */ + public static long max(long a, final long b, final long c) { + if (b > a) { + a = b; + } + if (c > a) { + a = c; + } + return a; + } + + /** + *

Gets the maximum of three int values.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the largest of the values + */ + public static int max(int a, final int b, final int c) { + if (b > a) { + a = b; + } + if (c > a) { + a = c; + } + return a; + } + + /** + *

Gets the maximum of three short values.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the largest of the values + */ + public static short max(short a, final short b, final short c) { + if (b > a) { + a = b; + } + if (c > a) { + a = c; + } + return a; + } + + /** + *

Gets the maximum of three byte values.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the largest of the values + */ + public static byte max(byte a, final byte b, final byte c) { + if (b > a) { + a = b; + } + if (c > a) { + a = c; + } + return a; + } + + /** + *

Gets the maximum of three double values.

+ * + *

If any value is NaN, NaN is + * returned. Infinity is handled.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the largest of the values + * @see IEEE754rUtils#max(double, double, double) for a version of this method that handles NaN differently + */ + public static double max(final double a, final double b, final double c) { + return Math.max(Math.max(a, b), c); + } + + /** + *

Gets the maximum of three float values.

+ * + *

If any value is NaN, NaN is + * returned. Infinity is handled.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the largest of the values + * @see IEEE754rUtils#max(float, float, float) for a version of this method that handles NaN differently + */ + public static float max(final float a, final float b, final float c) { + return Math.max(Math.max(a, b), c); + } + + //----------------------------------------------------------------------- + /** + *

Checks whether the String contains only + * digit characters.

+ * + *

Null and empty String will return + * false.

+ * + * @param str the String to check + * @return true if str contains only Unicode numeric + */ + public static boolean isDigits(final String str) { + return StringUtils.isNumeric(str); + } + + /** + *

Checks whether the String a valid Java number.

+ * + *

Valid numbers include hexadecimal marked with the 0x or + * 0X qualifier, octal numbers, scientific notation and + * numbers marked with a type qualifier (e.g. 123L).

+ * + *

Non-hexadecimal strings beginning with a leading zero are + * treated as octal values. Thus the string 09 will return + * false, since 9 is not a valid octal value. + * However, numbers beginning with {@code 0.} are treated as decimal.

+ * + *

null and empty/blank {@code String} will return + * false.

+ * + *

Note, {@link #createNumber(String)} should return a number for every + * input resuling in true.

+ * + * @param str the String to check + * @return true if the string is a correctly formatted number + * @since 3.3 the code supports hex {@code 0Xhhh} an + * octal {@code 0ddd} validation + * @deprecated This feature will be removed in Lang 4.0, + * use {@link NumberUtils#isCreatable(String)} instead + */ + @Deprecated + public static boolean isNumber(final String str) { + return isCreatable(str); + } + + /** + *

Checks whether the String a valid Java number.

+ * + *

Valid numbers include hexadecimal marked with the 0x or + * 0X qualifier, octal numbers, scientific notation and + * numbers marked with a type qualifier (e.g. 123L).

+ * + *

Non-hexadecimal strings beginning with a leading zero are + * treated as octal values. Thus the string 09 will return + * false, since 9 is not a valid octal value. + * However, numbers beginning with {@code 0.} are treated as decimal.

+ * + *

null and empty/blank {@code String} will return + * false.

+ * + *

Note, {@link #createNumber(String)} should return a number for every + * input resuling in true.

+ * + * @param str the String to check + * @return true if the string is a correctly formatted number + * @since 3.5 the code supports the "+" suffix on numbers except for integers in Java 1.6 + */ + public static boolean isCreatable(final String str) { + if (StringUtils.isEmpty(str)) { + return false; + } + final char[] chars = str.toCharArray(); + int sz = chars.length; + boolean hasExp = false; + boolean hasDecPoint = false; + boolean allowSigns = false; + boolean foundDigit = false; + // deal with any possible sign up front + final int start = chars[0] == '-' || chars[0] == '+' ? 1 : 0; + final boolean hasLeadingPlusSign = start == 1 && chars[0] == '+'; + if (sz > start + 1 && chars[start] == '0') { // leading 0 + if (chars[start + 1] == 'x' || chars[start + 1] == 'X') { // leading 0x/0X + int i = start + 2; + if (i == sz) { + return false; // str == "0x" + } + // checking hex (it can't be anything else) + for (; i < chars.length; i++) { + if ((chars[i] < '0' || chars[i] > '9') + && (chars[i] < 'a' || chars[i] > 'f') + && (chars[i] < 'A' || chars[i] > 'F')) { + return false; + } + } + return true; + } else if (Character.isDigit(chars[start + 1])) { + // leading 0, but not hex, must be octal + int i = start + 1; + for (; i < chars.length; i++) { + if (chars[i] < '0' || chars[i] > '7') { + return false; + } + } + return true; + } + } + sz--; // don't want to loop to the last char, check it afterwords + // for type qualifiers + int i = start; + // loop to the next to last char or to the last char if we need another digit to + // make a valid number (e.g. chars[0..5] = "1234E") + while (i < sz || i < sz + 1 && allowSigns && !foundDigit) { + if (chars[i] >= '0' && chars[i] <= '9') { + foundDigit = true; + allowSigns = false; + + } else if (chars[i] == '.') { + if (hasDecPoint || hasExp) { + // two decimal points or dec in exponent + return false; + } + hasDecPoint = true; + } else if (chars[i] == 'e' || chars[i] == 'E') { + // we've already taken care of hex. + if (hasExp) { + // two E's + return false; + } + if (!foundDigit) { + return false; + } + hasExp = true; + allowSigns = true; + } else if (chars[i] == '+' || chars[i] == '-') { + if (!allowSigns) { + return false; + } + allowSigns = false; + foundDigit = false; // we need a digit after the E + } else { + return false; + } + i++; + } + if (i < chars.length) { + if (chars[i] >= '0' && chars[i] <= '9') { + if (SystemUtils.IS_JAVA_1_6 && hasLeadingPlusSign && !hasDecPoint) { + return false; + } + // no type qualifier, OK + return true; + } + if (chars[i] == 'e' || chars[i] == 'E') { + // can't have an E at the last byte + return false; + } + if (chars[i] == '.') { + if (hasDecPoint || hasExp) { + // two decimal points or dec in exponent + return false; + } + // single trailing decimal point after non-exponent is ok + return foundDigit; + } + if (!allowSigns + && (chars[i] == 'd' + || chars[i] == 'D' + || chars[i] == 'f' + || chars[i] == 'F')) { + return foundDigit; + } + if (chars[i] == 'l' + || chars[i] == 'L') { + // not allowing L with an exponent or decimal point + return foundDigit && !hasExp && !hasDecPoint; + } + // last character is illegal + return false; + } + // allowSigns is true iff the val ends in 'E' + // found digit it to make sure weird stuff like '.' and '1E-' doesn't pass + return !allowSigns && foundDigit; + } + + /** + *

Checks whether the given String is a parsable number.

+ * + *

Parsable numbers include those Strings understood by {@link Integer#parseInt(String)}, + * {@link Long#parseLong(String)}, {@link Float#parseFloat(String)} or + * {@link Double#parseDouble(String)}. This method can be used instead of catching {@link java.text.ParseException} + * when calling one of those methods.

+ * + *

Hexadecimal and scientific notations are not considered parsable. + * See {@link #isCreatable(String)} on those cases.

+ * + *

{@code Null} and empty String will return false.

+ * + * @param str the String to check. + * @return {@code true} if the string is a parsable number. + * @since 3.4 + */ + public static boolean isParsable(final String str) { + if (StringUtils.isEmpty(str)) { + return false; + } + if (str.charAt(str.length() - 1) == '.') { + return false; + } + if (str.charAt(0) == '-') { + if (str.length() == 1) { + return false; + } + return withDecimalsParsing(str, 1); + } else { + return withDecimalsParsing(str, 0); + } + } + + private static boolean withDecimalsParsing(final String str, final int beginIdx) { + int decimalPoints = 0; + for (int i = beginIdx; i < str.length(); i++) { + final boolean isDecimalPoint = str.charAt(i) == '.'; + if (isDecimalPoint) { + decimalPoints++; + } + if (decimalPoints > 1) { + return false; + } + if (!isDecimalPoint && !Character.isDigit(str.charAt(i))) { + return false; + } + } + return true; + } + + /** + *

Compares two {@code int} values numerically. This is the same functionality as provided in Java 7.

+ * + * @param x the first {@code int} to compare + * @param y the second {@code int} 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(int x, int y) { + if (x == y) { + return 0; + } + return x < y ? -1 : 1; + } + + /** + *

Compares to {@code long} values numerically. This is the same functionality as provided in Java 7.

+ * + * @param x the first {@code long} to compare + * @param y the second {@code long} 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(long x, long y) { + if (x == y) { + return 0; + } + return x < y ? -1 : 1; + } + + /** + *

Compares to {@code short} values numerically. This is the same functionality as provided in Java 7.

+ * + * @param x the first {@code short} to compare + * @param y the second {@code short} 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(short x, short y) { + if (x == y) { + return 0; + } + return x < y ? -1 : 1; + } + + /** + *

Compares two {@code byte} values numerically. This is the same functionality as provided in Java 7.

+ * + * @param x the first {@code byte} to compare + * @param y the second {@code byte} 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(byte x, byte y) { + return x - y; + } +} diff --git a/Java/commons-lang-NumberUtils_452/metadata.json b/Java/commons-lang-NumberUtils_452/metadata.json new file mode 100644 index 000000000..1daf722dd --- /dev/null +++ b/Java/commons-lang-NumberUtils_452/metadata.json @@ -0,0 +1,21 @@ +{ + "language": "java", + "id": "commons-lang-NumberUtils_452", + "buggyPath": ".", + "referencePath": null, + "buildCommand": "mvn package -V -B -Denforcer.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true -Drat.skip=true -Dlicense.skip=true -Dfindbugs.skip=true -Dgpg.skip=true -Dskip.npm=true -Dskip.gulp=true -Dskip.bower=true -Drat.numUnapprovedLicenses=100 -DskipTests=true -DskipITs=true -Dtest=None -DfailIfNoTests=false", + "testCommand": "mvn test -V -B -Denforcer.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true -Drat.skip=true -Dlicense.skip=true -Dfindbugs.skip=true -Dgpg.skip=true -Dskip.npm=true -Dskip.gulp=true -Dskip.bower=true -Drat.numUnapprovedLicenses=100", + "categories": [ + "safety", + "npe" + ], + "npe": { + "filepath": "src/main/java/org/apache/commons/lang3/math/NumberUtils.java", + "line": 522, + "npe_method": "createNumber", + "deref_field": "str", + "npe_class": "NumberUtils", + "repo": "commons-lang", + "bug_id": "NumberUtils_452" + } +} diff --git a/Java/commons-lang-NumberUtils_452/npe.json b/Java/commons-lang-NumberUtils_452/npe.json new file mode 100644 index 000000000..b2b8fd4e6 --- /dev/null +++ b/Java/commons-lang-NumberUtils_452/npe.json @@ -0,0 +1,7 @@ +{ + "filepath": "src/main/java/org/apache/commons/lang3/math/NumberUtils.java", + "line": 522, + "npe_method": "createNumber", + "deref_field": "str", + "npe_class": "NumberUtils" +} \ No newline at end of file diff --git a/Java/commons-lang-NumberUtils_657/Dockerfile b/Java/commons-lang-NumberUtils_657/Dockerfile new file mode 100644 index 000000000..7b7fbe349 --- /dev/null +++ b/Java/commons-lang-NumberUtils_657/Dockerfile @@ -0,0 +1,18 @@ +FROM ghcr.io/kupl/starlab-benchmarks/java-base:commons-lang + +ENV TZ=Asia/Seoul + +COPY ./metadata.json . +COPY ./npe.json . +COPY ./buggy.java /tmp/buggy.java +RUN export BUGGY_PATH=$(cat metadata.json | jq -r ".npe.filepath") \ + && export BUGGY_LINE=$(cat metadata.json | jq -r ".npe.line") \ + && export BUGGY_MTHD=$(cat metadata.json | jq -r ".npe.npe_method") \ + && mv /tmp/buggy.java $BUGGY_PATH \ + && echo "[{\"filepath\": \"$BUGGY_PATH\", \"line\": $BUGGY_LINE, \"method_name\": \"$BUGGY_MTHD\"}]" | jq . > traces.json + +RUN git init . && git add -A + +RUN $(cat metadata.json | jq -r ".buildCommand") + +RUN $(cat metadata.json | jq -r ".testCommand"); if [ $? -eq 0 ]; then exit 1; fi diff --git a/Java/commons-lang-NumberUtils_657/buggy.java b/Java/commons-lang-NumberUtils_657/buggy.java new file mode 100644 index 000000000..b80eae120 --- /dev/null +++ b/Java/commons-lang-NumberUtils_657/buggy.java @@ -0,0 +1,1642 @@ +/* + * 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 java.lang.reflect.Array; +import java.math.BigDecimal; +import java.math.BigInteger; + +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.SystemUtils; +import org.apache.commons.lang3.Validate; + +/** + *

Provides extra functionality for Java Number classes.

+ * + * @since 2.0 + */ +public class NumberUtils { + + /** Reusable Long constant for zero. */ + public static final Long LONG_ZERO = Long.valueOf(0L); + /** Reusable Long constant for one. */ + public static final Long LONG_ONE = Long.valueOf(1L); + /** Reusable Long constant for minus one. */ + public static final Long LONG_MINUS_ONE = Long.valueOf(-1L); + /** Reusable Integer constant for zero. */ + public static final Integer INTEGER_ZERO = Integer.valueOf(0); + /** Reusable Integer constant for one. */ + public static final Integer INTEGER_ONE = Integer.valueOf(1); + /** Reusable Integer constant for minus one. */ + public static final Integer INTEGER_MINUS_ONE = Integer.valueOf(-1); + /** Reusable Short constant for zero. */ + public static final Short SHORT_ZERO = Short.valueOf((short) 0); + /** Reusable Short constant for one. */ + public static final Short SHORT_ONE = Short.valueOf((short) 1); + /** Reusable Short constant for minus one. */ + public static final Short SHORT_MINUS_ONE = Short.valueOf((short) -1); + /** Reusable Byte constant for zero. */ + public static final Byte BYTE_ZERO = Byte.valueOf((byte) 0); + /** Reusable Byte constant for one. */ + public static final Byte BYTE_ONE = Byte.valueOf((byte) 1); + /** Reusable Byte constant for minus one. */ + public static final Byte BYTE_MINUS_ONE = Byte.valueOf((byte) -1); + /** Reusable Double constant for zero. */ + public static final Double DOUBLE_ZERO = Double.valueOf(0.0d); + /** Reusable Double constant for one. */ + public static final Double DOUBLE_ONE = Double.valueOf(1.0d); + /** Reusable Double constant for minus one. */ + public static final Double DOUBLE_MINUS_ONE = Double.valueOf(-1.0d); + /** Reusable Float constant for zero. */ + public static final Float FLOAT_ZERO = Float.valueOf(0.0f); + /** Reusable Float constant for one. */ + public static final Float FLOAT_ONE = Float.valueOf(1.0f); + /** Reusable Float constant for minus one. */ + public static final Float FLOAT_MINUS_ONE = Float.valueOf(-1.0f); + + /** + *

NumberUtils instances should NOT be constructed in standard programming. + * Instead, the class should be used as NumberUtils.toInt("6");.

+ * + *

This constructor is public to permit tools that require a JavaBean instance + * to operate.

+ */ + public NumberUtils() { + super(); + } + + //----------------------------------------------------------------------- + /** + *

Convert a String to an int, returning + * zero if the conversion fails.

+ * + *

If the string is null, zero is returned.

+ * + *
+     *   NumberUtils.toInt(null) = 0
+     *   NumberUtils.toInt("")   = 0
+     *   NumberUtils.toInt("1")  = 1
+     * 
+ * + * @param str the string to convert, may be null + * @return the int represented by the string, or zero if + * conversion fails + * @since 2.1 + */ + public static int toInt(final String str) { + return toInt(str, 0); + } + + /** + *

Convert a String to an int, returning a + * default value if the conversion fails.

+ * + *

If the string is null, the default value is returned.

+ * + *
+     *   NumberUtils.toInt(null, 1) = 1
+     *   NumberUtils.toInt("", 1)   = 1
+     *   NumberUtils.toInt("1", 0)  = 1
+     * 
+ * + * @param str the string to convert, may be null + * @param defaultValue the default value + * @return the int represented by the string, or the default if conversion fails + * @since 2.1 + */ + public static int toInt(final String str, final int defaultValue) { + if(str == null) { + return defaultValue; + } + try { + return Integer.parseInt(str); + } catch (final NumberFormatException nfe) { + return defaultValue; + } + } + + /** + *

Convert a String to a long, returning + * zero if the conversion fails.

+ * + *

If the string is null, zero is returned.

+ * + *
+     *   NumberUtils.toLong(null) = 0L
+     *   NumberUtils.toLong("")   = 0L
+     *   NumberUtils.toLong("1")  = 1L
+     * 
+ * + * @param str the string to convert, may be null + * @return the long represented by the string, or 0 if + * conversion fails + * @since 2.1 + */ + public static long toLong(final String str) { + return toLong(str, 0L); + } + + /** + *

Convert a String to a long, returning a + * default value if the conversion fails.

+ * + *

If the string is null, the default value is returned.

+ * + *
+     *   NumberUtils.toLong(null, 1L) = 1L
+     *   NumberUtils.toLong("", 1L)   = 1L
+     *   NumberUtils.toLong("1", 0L)  = 1L
+     * 
+ * + * @param str the string to convert, may be null + * @param defaultValue the default value + * @return the long represented by the string, or the default if conversion fails + * @since 2.1 + */ + public static long toLong(final String str, final long defaultValue) { + if (str == null) { + return defaultValue; + } + try { + return Long.parseLong(str); + } catch (final NumberFormatException nfe) { + return defaultValue; + } + } + + /** + *

Convert a String to a float, returning + * 0.0f if the conversion fails.

+ * + *

If the string str is null, + * 0.0f is returned.

+ * + *
+     *   NumberUtils.toFloat(null)   = 0.0f
+     *   NumberUtils.toFloat("")     = 0.0f
+     *   NumberUtils.toFloat("1.5")  = 1.5f
+     * 
+ * + * @param str the string to convert, may be null + * @return the float represented by the string, or 0.0f + * if conversion fails + * @since 2.1 + */ + public static float toFloat(final String str) { + return toFloat(str, 0.0f); + } + + /** + *

Convert a String to a float, returning a + * default value if the conversion fails.

+ * + *

If the string str is null, the default + * value is returned.

+ * + *
+     *   NumberUtils.toFloat(null, 1.1f)   = 1.0f
+     *   NumberUtils.toFloat("", 1.1f)     = 1.1f
+     *   NumberUtils.toFloat("1.5", 0.0f)  = 1.5f
+     * 
+ * + * @param str the string to convert, may be null + * @param defaultValue the default value + * @return the float represented by the string, or defaultValue + * if conversion fails + * @since 2.1 + */ + public static float toFloat(final String str, final float defaultValue) { + if (str == null) { + return defaultValue; + } + try { + return Float.parseFloat(str); + } catch (final NumberFormatException nfe) { + return defaultValue; + } + } + + /** + *

Convert a String to a double, returning + * 0.0d if the conversion fails.

+ * + *

If the string str is null, + * 0.0d is returned.

+ * + *
+     *   NumberUtils.toDouble(null)   = 0.0d
+     *   NumberUtils.toDouble("")     = 0.0d
+     *   NumberUtils.toDouble("1.5")  = 1.5d
+     * 
+ * + * @param str the string to convert, may be null + * @return the double represented by the string, or 0.0d + * if conversion fails + * @since 2.1 + */ + public static double toDouble(final String str) { + return toDouble(str, 0.0d); + } + + /** + *

Convert a String to a double, returning a + * default value if the conversion fails.

+ * + *

If the string str is null, the default + * value is returned.

+ * + *
+     *   NumberUtils.toDouble(null, 1.1d)   = 1.1d
+     *   NumberUtils.toDouble("", 1.1d)     = 1.1d
+     *   NumberUtils.toDouble("1.5", 0.0d)  = 1.5d
+     * 
+ * + * @param str the string to convert, may be null + * @param defaultValue the default value + * @return the double represented by the string, or defaultValue + * if conversion fails + * @since 2.1 + */ + public static double toDouble(final String str, final double defaultValue) { + if (str == null) { + return defaultValue; + } + try { + return Double.parseDouble(str); + } catch (final NumberFormatException nfe) { + return defaultValue; + } + } + + //----------------------------------------------------------------------- + /** + *

Convert a String to a byte, returning + * zero if the conversion fails.

+ * + *

If the string is null, zero is returned.

+ * + *
+     *   NumberUtils.toByte(null) = 0
+     *   NumberUtils.toByte("")   = 0
+     *   NumberUtils.toByte("1")  = 1
+     * 
+ * + * @param str the string to convert, may be null + * @return the byte represented by the string, or zero if + * conversion fails + * @since 2.5 + */ + public static byte toByte(final String str) { + return toByte(str, (byte) 0); + } + + /** + *

Convert a String to a byte, returning a + * default value if the conversion fails.

+ * + *

If the string is null, the default value is returned.

+ * + *
+     *   NumberUtils.toByte(null, 1) = 1
+     *   NumberUtils.toByte("", 1)   = 1
+     *   NumberUtils.toByte("1", 0)  = 1
+     * 
+ * + * @param str the string to convert, may be null + * @param defaultValue the default value + * @return the byte represented by the string, or the default if conversion fails + * @since 2.5 + */ + public static byte toByte(final String str, final byte defaultValue) { + if(str == null) { + return defaultValue; + } + try { + return Byte.parseByte(str); + } catch (final NumberFormatException nfe) { + return defaultValue; + } + } + + /** + *

Convert a String to a short, returning + * zero if the conversion fails.

+ * + *

If the string is null, zero is returned.

+ * + *
+     *   NumberUtils.toShort(null) = 0
+     *   NumberUtils.toShort("")   = 0
+     *   NumberUtils.toShort("1")  = 1
+     * 
+ * + * @param str the string to convert, may be null + * @return the short represented by the string, or zero if + * conversion fails + * @since 2.5 + */ + public static short toShort(final String str) { + return toShort(str, (short) 0); + } + + /** + *

Convert a String to an short, returning a + * default value if the conversion fails.

+ * + *

If the string is null, the default value is returned.

+ * + *
+     *   NumberUtils.toShort(null, 1) = 1
+     *   NumberUtils.toShort("", 1)   = 1
+     *   NumberUtils.toShort("1", 0)  = 1
+     * 
+ * + * @param str the string to convert, may be null + * @param defaultValue the default value + * @return the short represented by the string, or the default if conversion fails + * @since 2.5 + */ + public static short toShort(final String str, final short defaultValue) { + if(str == null) { + return defaultValue; + } + try { + return Short.parseShort(str); + } catch (final NumberFormatException nfe) { + return defaultValue; + } + } + + //----------------------------------------------------------------------- + // must handle Long, Float, Integer, Float, Short, + // BigDecimal, BigInteger and Byte + // useful methods: + // Byte.decode(String) + // Byte.valueOf(String,int radix) + // Byte.valueOf(String) + // Double.valueOf(String) + // Float.valueOf(String) + // Float.valueOf(String) + // Integer.valueOf(String,int radix) + // Integer.valueOf(String) + // Integer.decode(String) + // Integer.getInteger(String) + // Integer.getInteger(String,int val) + // Integer.getInteger(String,Integer val) + // Integer.valueOf(String) + // Double.valueOf(String) + // new Byte(String) + // Long.valueOf(String) + // Long.getLong(String) + // Long.getLong(String,int) + // Long.getLong(String,Integer) + // Long.valueOf(String,int) + // Long.valueOf(String) + // Short.valueOf(String) + // Short.decode(String) + // Short.valueOf(String,int) + // Short.valueOf(String) + // new BigDecimal(String) + // new BigInteger(String) + // new BigInteger(String,int radix) + // Possible inputs: + // 45 45.5 45E7 4.5E7 Hex Oct Binary xxxF xxxD xxxf xxxd + // plus minus everything. Prolly more. A lot are not separable. + + /** + *

Turns a string value into a java.lang.Number.

+ * + *

If the string starts with {@code 0x} or {@code -0x} (lower or upper case) or {@code #} or {@code -#}, it + * will be interpreted as a hexadecimal Integer - or Long, if the number of digits after the + * prefix is more than 8 - or BigInteger if there are more than 16 digits. + *

+ *

Then, the value is examined for a type qualifier on the end, i.e. one of + * 'f','F','d','D','l','L'. If it is found, it starts + * trying to create successively larger types from the type specified + * until one is found that can represent the value.

+ * + *

If a type specifier is not found, it will check for a decimal point + * and then try successively larger types from Integer to + * BigInteger and from Float to + * BigDecimal.

+ * + *

+ * Integral values with a leading {@code 0} will be interpreted as octal; the returned number will + * be Integer, Long or BigDecimal as appropriate. + *

+ * + *

Returns null if the string is null.

+ * + *

This method does not trim the input string, i.e., strings with leading + * or trailing spaces will generate NumberFormatExceptions.

+ * + * @param str String containing a number, may be null + * @return Number created from the string (or null if the input is null) + * @throws NumberFormatException if the value cannot be converted + */ + public static Number createNumber(final String str) throws NumberFormatException { + if (str == null) { + return null; + } + if (StringUtils.isBlank(str)) { + throw new NumberFormatException("A blank string is not a valid number"); + } + // Need to deal with all possible hex prefixes here + final String[] hex_prefixes = {"0x", "0X", "-0x", "-0X", "#", "-#"}; + int pfxLen = 0; + for(final String pfx : hex_prefixes) { + if (str.startsWith(pfx)) { + pfxLen += pfx.length(); + break; + } + } + if (pfxLen > 0) { // we have a hex number + char firstSigDigit = 0; // strip leading zeroes + for(int i = pfxLen; i < str.length(); i++) { + firstSigDigit = str.charAt(i); + if (firstSigDigit == '0') { // count leading zeroes + pfxLen++; + } else { + break; + } + } + final int hexDigits = str.length() - pfxLen; + if (hexDigits > 16 || hexDigits == 16 && firstSigDigit > '7') { // too many for Long + return createBigInteger(str); + } + if (hexDigits > 8 || hexDigits == 8 && firstSigDigit > '7') { // too many for an int + return createLong(str); + } + return createInteger(str); + } + final char lastChar = str.charAt(str.length() - 1); + String mant; + String dec; + String exp; + final int decPos = str.indexOf('.'); + final int expPos = str.indexOf('e') + str.indexOf('E') + 1; // assumes both not present + // if both e and E are present, this is caught by the checks on expPos (which prevent IOOBE) + // and the parsing which will detect if e or E appear in a number due to using the wrong offset + + if (decPos > -1) { // there is a decimal point + if (expPos > -1) { // there is an exponent + if (expPos < decPos || expPos > str.length()) { // prevents double exponent causing IOOBE + throw new NumberFormatException(str + " is not a valid number."); + } + dec = str.substring(decPos + 1, expPos); + } else { + dec = str.substring(decPos + 1); + } + mant = getMantissa(str, decPos); + } else { + if (expPos > -1) { + if (expPos > str.length()) { // prevents double exponent causing IOOBE + throw new NumberFormatException(str + " is not a valid number."); + } + mant = getMantissa(str, expPos); + } else { + mant = getMantissa(str); + } + dec = null; + } + if (!Character.isDigit(lastChar) && lastChar != '.') { + if (expPos > -1 && expPos < str.length() - 1) { + exp = str.substring(expPos + 1, str.length() - 1); + } else { + exp = null; + } + //Requesting a specific type.. + final String numeric = str.substring(0, str.length() - 1); + final boolean allZeros = isAllZeros(mant) && isAllZeros(exp); + switch (lastChar) { + case 'l' : + case 'L' : + if (dec == null + && exp == null + && (numeric.charAt(0) == '-' && isDigits(numeric.substring(1)) || isDigits(numeric))) { + try { + return createLong(numeric); + } catch (final NumberFormatException nfe) { // NOPMD + // Too big for a long + } + return createBigInteger(numeric); + + } + throw new NumberFormatException(str + " is not a valid number."); + case 'f' : + case 'F' : + try { + final Float f = NumberUtils.createFloat(str); + if (!(f.isInfinite() || f.floatValue() == 0.0F && !allZeros)) { + //If it's too big for a float or the float value = 0 and the string + //has non-zeros in it, then float does not have the precision we want + return f; + } + + } catch (final NumberFormatException nfe) { // NOPMD + // ignore the bad number + } + //$FALL-THROUGH$ + case 'd' : + case 'D' : + try { + final Double d = NumberUtils.createDouble(str); + if (!(d.isInfinite() || d.floatValue() == 0.0D && !allZeros)) { + return d; + } + } catch (final NumberFormatException nfe) { // NOPMD + // ignore the bad number + } + try { + return createBigDecimal(numeric); + } catch (final NumberFormatException e) { // NOPMD + // ignore the bad number + } + //$FALL-THROUGH$ + default : + throw new NumberFormatException(str + " is not a valid number."); + + } + } + //User doesn't have a preference on the return type, so let's start + //small and go from there... + if (expPos > -1 && expPos < str.length() - 1) { + exp = str.substring(expPos + 1, str.length()); + } else { + exp = null; + } + if (dec == null && exp == null) { // no decimal point and no exponent + //Must be an Integer, Long, Biginteger + try { + return createInteger(str); + } catch (final NumberFormatException nfe) { // NOPMD + // ignore the bad number + } + try { + return createLong(str); + } catch (final NumberFormatException nfe) { // NOPMD + // ignore the bad number + } + return createBigInteger(str); + } + + //Must be a Float, Double, BigDecimal + final boolean allZeros = isAllZeros(mant) && isAllZeros(exp); + try { + final Float f = createFloat(str); + final Double d = createDouble(str); + if (!f.isInfinite() + && !(f.floatValue() == 0.0F && !allZeros) + && f.toString().equals(d.toString())) { + return f; + } + if (!d.isInfinite() && !(d.doubleValue() == 0.0D && !allZeros)) { + final BigDecimal b = createBigDecimal(str); + if (b.compareTo(BigDecimal.valueOf(d)) == 0) { + return d; + } + return b; + } + } catch (final NumberFormatException nfe) { // NOPMD + // ignore the bad number + } + return createBigDecimal(str); + } + + /** + *

Utility method for {@link #createNumber(java.lang.String)}.

+ * + *

Returns mantissa of the given number.

+ * + * @param str the string representation of the number + * @return mantissa of the given number + */ + private static String getMantissa(final String str) { + return getMantissa(str, str.length()); + } + + /** + *

Utility method for {@link #createNumber(java.lang.String)}.

+ * + *

Returns mantissa of the given number.

+ * + * @param str the string representation of the number + * @param stopPos the position of the exponent or decimal point + * @return mantissa of the given number + */ + private static String getMantissa(final String str, final int stopPos) { + final char firstChar = str.charAt(0); + final boolean hasSign = firstChar == '-' || firstChar == '+'; + + return hasSign ? str.substring(1, stopPos) : str.substring(0, stopPos); + } + + /** + *

Utility method for {@link #createNumber(java.lang.String)}.

+ * + *

Returns true if s is null.

+ * + * @param str the String to check + * @return if it is all zeros or null + */ +/** + *

Utility method for {@link #createNumber(java.lang.String)}.

+ * + *

Returns true if s is null.

+ * + * @param str + * the String to check + * @return if it is all zeros or null + */ +private static boolean isAllZeros(final java.lang.String str) { + { + for (int i = /* NPEX_NULL_EXP */ + str.length() - 1; i >= 0; i--) { + if (str.charAt(i) != '0') { + return false; + } + } + return str.length() > 0; + } +} + + //----------------------------------------------------------------------- + /** + *

Convert a String to a Float.

+ * + *

Returns null if the string is null.

+ * + * @param str a String to convert, may be null + * @return converted Float (or null if the input is null) + * @throws NumberFormatException if the value cannot be converted + */ + public static Float createFloat(final String str) { + if (str == null) { + return null; + } + return Float.valueOf(str); + } + + /** + *

Convert a String to a Double.

+ * + *

Returns null if the string is null.

+ * + * @param str a String to convert, may be null + * @return converted Double (or null if the input is null) + * @throws NumberFormatException if the value cannot be converted + */ + public static Double createDouble(final String str) { + if (str == null) { + return null; + } + return Double.valueOf(str); + } + + /** + *

Convert a String to a Integer, handling + * hex (0xhhhh) and octal (0dddd) notations. + * N.B. a leading zero means octal; spaces are not trimmed.

+ * + *

Returns null if the string is null.

+ * + * @param str a String to convert, may be null + * @return converted Integer (or null if the input is null) + * @throws NumberFormatException if the value cannot be converted + */ + public static Integer createInteger(final String str) { + if (str == null) { + return null; + } + // decode() handles 0xAABD and 0777 (hex and octal) as well. + return Integer.decode(str); + } + + /** + *

Convert a String to a Long; + * since 3.1 it handles hex (0Xhhhh) and octal (0ddd) notations. + * N.B. a leading zero means octal; spaces are not trimmed.

+ * + *

Returns null if the string is null.

+ * + * @param str a String to convert, may be null + * @return converted Long (or null if the input is null) + * @throws NumberFormatException if the value cannot be converted + */ + public static Long createLong(final String str) { + if (str == null) { + return null; + } + return Long.decode(str); + } + + /** + *

Convert a String to a BigInteger; + * since 3.2 it handles hex (0x or #) and octal (0) notations.

+ * + *

Returns null if the string is null.

+ * + * @param str a String to convert, may be null + * @return converted BigInteger (or null if the input is null) + * @throws NumberFormatException if the value cannot be converted + */ + public static BigInteger createBigInteger(final String str) { + if (str == null) { + return null; + } + int pos = 0; // offset within string + int radix = 10; + boolean negate = false; // need to negate later? + if (str.startsWith("-")) { + negate = true; + pos = 1; + } + if (str.startsWith("0x", pos) || str.startsWith("0X", pos)) { // hex + radix = 16; + pos += 2; + } else if (str.startsWith("#", pos)) { // alternative hex (allowed by Long/Integer) + radix = 16; + pos ++; + } else if (str.startsWith("0", pos) && str.length() > pos + 1) { // octal; so long as there are additional digits + radix = 8; + pos ++; + } // default is to treat as decimal + + final BigInteger value = new BigInteger(str.substring(pos), radix); + return negate ? value.negate() : value; + } + + /** + *

Convert a String to a BigDecimal.

+ * + *

Returns null if the string is null.

+ * + * @param str a String to convert, may be null + * @return converted BigDecimal (or null if the input is null) + * @throws NumberFormatException if the value cannot be converted + */ + public static BigDecimal createBigDecimal(final String str) { + if (str == null) { + return null; + } + // handle JDK1.3.1 bug where "" throws IndexOutOfBoundsException + if (StringUtils.isBlank(str)) { + throw new NumberFormatException("A blank string is not a valid number"); + } + if (str.trim().startsWith("--")) { + // this is protection for poorness in java.lang.BigDecimal. + // it accepts this as a legal value, but it does not appear + // to be in specification of class. OS X Java parses it to + // a wrong value. + throw new NumberFormatException(str + " is not a valid number."); + } + return new BigDecimal(str); + } + + // Min in array + //-------------------------------------------------------------------- + /** + *

Returns the minimum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the minimum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @since 3.4 Changed signature from min(long[]) to min(long...) + */ + public static long min(final long... array) { + // Validates input + validateArray(array); + + // Finds and returns min + long min = array[0]; + for (int i = 1; i < array.length; i++) { + if (array[i] < min) { + min = array[i]; + } + } + + return min; + } + + /** + *

Returns the minimum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the minimum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @since 3.4 Changed signature from min(int[]) to min(int...) + */ + public static int min(final int... array) { + // Validates input + validateArray(array); + + // Finds and returns min + int min = array[0]; + for (int j = 1; j < array.length; j++) { + if (array[j] < min) { + min = array[j]; + } + } + + return min; + } + + /** + *

Returns the minimum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the minimum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @since 3.4 Changed signature from min(short[]) to min(short...) + */ + public static short min(final short... array) { + // Validates input + validateArray(array); + + // Finds and returns min + short min = array[0]; + for (int i = 1; i < array.length; i++) { + if (array[i] < min) { + min = array[i]; + } + } + + return min; + } + + /** + *

Returns the minimum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the minimum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @since 3.4 Changed signature from min(byte[]) to min(byte...) + */ + public static byte min(final byte... array) { + // Validates input + validateArray(array); + + // Finds and returns min + byte min = array[0]; + for (int i = 1; i < array.length; i++) { + if (array[i] < min) { + min = array[i]; + } + } + + return min; + } + + /** + *

Returns the minimum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the minimum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @see IEEE754rUtils#min(double[]) IEEE754rUtils for a version of this method that handles NaN differently + * @since 3.4 Changed signature from min(double[]) to min(double...) + */ + public static double min(final double... array) { + // Validates input + validateArray(array); + + // Finds and returns min + double min = array[0]; + for (int i = 1; i < array.length; i++) { + if (Double.isNaN(array[i])) { + return Double.NaN; + } + if (array[i] < min) { + min = array[i]; + } + } + + return min; + } + + /** + *

Returns the minimum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the minimum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @see IEEE754rUtils#min(float[]) IEEE754rUtils for a version of this method that handles NaN differently + * @since 3.4 Changed signature from min(float[]) to min(float...) + */ + public static float min(final float... array) { + // Validates input + validateArray(array); + + // Finds and returns min + float min = array[0]; + for (int i = 1; i < array.length; i++) { + if (Float.isNaN(array[i])) { + return Float.NaN; + } + if (array[i] < min) { + min = array[i]; + } + } + + return min; + } + + // Max in array + //-------------------------------------------------------------------- + /** + *

Returns the maximum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the maximum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @since 3.4 Changed signature from max(long[]) to max(long...) + */ + public static long max(final long... array) { + // Validates input + validateArray(array); + + // Finds and returns max + long max = array[0]; + for (int j = 1; j < array.length; j++) { + if (array[j] > max) { + max = array[j]; + } + } + + return max; + } + + /** + *

Returns the maximum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the maximum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @since 3.4 Changed signature from max(int[]) to max(int...) + */ + public static int max(final int... array) { + // Validates input + validateArray(array); + + // Finds and returns max + int max = array[0]; + for (int j = 1; j < array.length; j++) { + if (array[j] > max) { + max = array[j]; + } + } + + return max; + } + + /** + *

Returns the maximum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the maximum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @since 3.4 Changed signature from max(short[]) to max(short...) + */ + public static short max(final short... array) { + // Validates input + validateArray(array); + + // Finds and returns max + short max = array[0]; + for (int i = 1; i < array.length; i++) { + if (array[i] > max) { + max = array[i]; + } + } + + return max; + } + + /** + *

Returns the maximum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the maximum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @since 3.4 Changed signature from max(byte[]) to max(byte...) + */ + public static byte max(final byte... array) { + // Validates input + validateArray(array); + + // Finds and returns max + byte max = array[0]; + for (int i = 1; i < array.length; i++) { + if (array[i] > max) { + max = array[i]; + } + } + + return max; + } + + /** + *

Returns the maximum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the maximum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @see IEEE754rUtils#max(double[]) IEEE754rUtils for a version of this method that handles NaN differently + * @since 3.4 Changed signature from max(double[]) to max(double...) + */ + public static double max(final double... array) { + // Validates input + validateArray(array); + + // Finds and returns max + double max = array[0]; + for (int j = 1; j < array.length; j++) { + if (Double.isNaN(array[j])) { + return Double.NaN; + } + if (array[j] > max) { + max = array[j]; + } + } + + return max; + } + + /** + *

Returns the maximum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the maximum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @see IEEE754rUtils#max(float[]) IEEE754rUtils for a version of this method that handles NaN differently + * @since 3.4 Changed signature from max(float[]) to max(float...) + */ + public static float max(final float... array) { + // Validates input + validateArray(array); + + // Finds and returns max + float max = array[0]; + for (int j = 1; j < array.length; j++) { + if (Float.isNaN(array[j])) { + return Float.NaN; + } + if (array[j] > max) { + max = array[j]; + } + } + + return max; + } + + /** + * Checks if the specified array is neither null nor empty. + * + * @param array the array to check + * @throws IllegalArgumentException if {@code array} is either {@code null} or empty + */ + private static void validateArray(final Object array) { + if (array == null) { + throw new IllegalArgumentException("The Array must not be null"); + } + Validate.isTrue(Array.getLength(array) != 0, "Array cannot be empty."); + } + + // 3 param min + //----------------------------------------------------------------------- + /** + *

Gets the minimum of three long values.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the smallest of the values + */ + public static long min(long a, final long b, final long c) { + if (b < a) { + a = b; + } + if (c < a) { + a = c; + } + return a; + } + + /** + *

Gets the minimum of three int values.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the smallest of the values + */ + public static int min(int a, final int b, final int c) { + if (b < a) { + a = b; + } + if (c < a) { + a = c; + } + return a; + } + + /** + *

Gets the minimum of three short values.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the smallest of the values + */ + public static short min(short a, final short b, final short c) { + if (b < a) { + a = b; + } + if (c < a) { + a = c; + } + return a; + } + + /** + *

Gets the minimum of three byte values.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the smallest of the values + */ + public static byte min(byte a, final byte b, final byte c) { + if (b < a) { + a = b; + } + if (c < a) { + a = c; + } + return a; + } + + /** + *

Gets the minimum of three double values.

+ * + *

If any value is NaN, NaN is + * returned. Infinity is handled.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the smallest of the values + * @see IEEE754rUtils#min(double, double, double) for a version of this method that handles NaN differently + */ + public static double min(final double a, final double b, final double c) { + return Math.min(Math.min(a, b), c); + } + + /** + *

Gets the minimum of three float values.

+ * + *

If any value is NaN, NaN is + * returned. Infinity is handled.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the smallest of the values + * @see IEEE754rUtils#min(float, float, float) for a version of this method that handles NaN differently + */ + public static float min(final float a, final float b, final float c) { + return Math.min(Math.min(a, b), c); + } + + // 3 param max + //----------------------------------------------------------------------- + /** + *

Gets the maximum of three long values.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the largest of the values + */ + public static long max(long a, final long b, final long c) { + if (b > a) { + a = b; + } + if (c > a) { + a = c; + } + return a; + } + + /** + *

Gets the maximum of three int values.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the largest of the values + */ + public static int max(int a, final int b, final int c) { + if (b > a) { + a = b; + } + if (c > a) { + a = c; + } + return a; + } + + /** + *

Gets the maximum of three short values.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the largest of the values + */ + public static short max(short a, final short b, final short c) { + if (b > a) { + a = b; + } + if (c > a) { + a = c; + } + return a; + } + + /** + *

Gets the maximum of three byte values.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the largest of the values + */ + public static byte max(byte a, final byte b, final byte c) { + if (b > a) { + a = b; + } + if (c > a) { + a = c; + } + return a; + } + + /** + *

Gets the maximum of three double values.

+ * + *

If any value is NaN, NaN is + * returned. Infinity is handled.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the largest of the values + * @see IEEE754rUtils#max(double, double, double) for a version of this method that handles NaN differently + */ + public static double max(final double a, final double b, final double c) { + return Math.max(Math.max(a, b), c); + } + + /** + *

Gets the maximum of three float values.

+ * + *

If any value is NaN, NaN is + * returned. Infinity is handled.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the largest of the values + * @see IEEE754rUtils#max(float, float, float) for a version of this method that handles NaN differently + */ + public static float max(final float a, final float b, final float c) { + return Math.max(Math.max(a, b), c); + } + + //----------------------------------------------------------------------- + /** + *

Checks whether the String contains only + * digit characters.

+ * + *

Null and empty String will return + * false.

+ * + * @param str the String to check + * @return true if str contains only Unicode numeric + */ + public static boolean isDigits(final String str) { + return StringUtils.isNumeric(str); + } + + /** + *

Checks whether the String a valid Java number.

+ * + *

Valid numbers include hexadecimal marked with the 0x or + * 0X qualifier, octal numbers, scientific notation and + * numbers marked with a type qualifier (e.g. 123L).

+ * + *

Non-hexadecimal strings beginning with a leading zero are + * treated as octal values. Thus the string 09 will return + * false, since 9 is not a valid octal value. + * However, numbers beginning with {@code 0.} are treated as decimal.

+ * + *

null and empty/blank {@code String} will return + * false.

+ * + *

Note, {@link #createNumber(String)} should return a number for every + * input resuling in true.

+ * + * @param str the String to check + * @return true if the string is a correctly formatted number + * @since 3.3 the code supports hex {@code 0Xhhh} an + * octal {@code 0ddd} validation + * @deprecated This feature will be removed in Lang 4.0, + * use {@link NumberUtils#isCreatable(String)} instead + */ + @Deprecated + public static boolean isNumber(final String str) { + return isCreatable(str); + } + + /** + *

Checks whether the String a valid Java number.

+ * + *

Valid numbers include hexadecimal marked with the 0x or + * 0X qualifier, octal numbers, scientific notation and + * numbers marked with a type qualifier (e.g. 123L).

+ * + *

Non-hexadecimal strings beginning with a leading zero are + * treated as octal values. Thus the string 09 will return + * false, since 9 is not a valid octal value. + * However, numbers beginning with {@code 0.} are treated as decimal.

+ * + *

null and empty/blank {@code String} will return + * false.

+ * + *

Note, {@link #createNumber(String)} should return a number for every + * input resuling in true.

+ * + * @param str the String to check + * @return true if the string is a correctly formatted number + * @since 3.5 the code supports the "+" suffix on numbers except for integers in Java 1.6 + */ + public static boolean isCreatable(final String str) { + if (StringUtils.isEmpty(str)) { + return false; + } + final char[] chars = str.toCharArray(); + int sz = chars.length; + boolean hasExp = false; + boolean hasDecPoint = false; + boolean allowSigns = false; + boolean foundDigit = false; + // deal with any possible sign up front + final int start = chars[0] == '-' || chars[0] == '+' ? 1 : 0; + final boolean hasLeadingPlusSign = start == 1 && chars[0] == '+'; + if (sz > start + 1 && chars[start] == '0') { // leading 0 + if (chars[start + 1] == 'x' || chars[start + 1] == 'X') { // leading 0x/0X + int i = start + 2; + if (i == sz) { + return false; // str == "0x" + } + // checking hex (it can't be anything else) + for (; i < chars.length; i++) { + if ((chars[i] < '0' || chars[i] > '9') + && (chars[i] < 'a' || chars[i] > 'f') + && (chars[i] < 'A' || chars[i] > 'F')) { + return false; + } + } + return true; + } else if (Character.isDigit(chars[start + 1])) { + // leading 0, but not hex, must be octal + int i = start + 1; + for (; i < chars.length; i++) { + if (chars[i] < '0' || chars[i] > '7') { + return false; + } + } + return true; + } + } + sz--; // don't want to loop to the last char, check it afterwords + // for type qualifiers + int i = start; + // loop to the next to last char or to the last char if we need another digit to + // make a valid number (e.g. chars[0..5] = "1234E") + while (i < sz || i < sz + 1 && allowSigns && !foundDigit) { + if (chars[i] >= '0' && chars[i] <= '9') { + foundDigit = true; + allowSigns = false; + + } else if (chars[i] == '.') { + if (hasDecPoint || hasExp) { + // two decimal points or dec in exponent + return false; + } + hasDecPoint = true; + } else if (chars[i] == 'e' || chars[i] == 'E') { + // we've already taken care of hex. + if (hasExp) { + // two E's + return false; + } + if (!foundDigit) { + return false; + } + hasExp = true; + allowSigns = true; + } else if (chars[i] == '+' || chars[i] == '-') { + if (!allowSigns) { + return false; + } + allowSigns = false; + foundDigit = false; // we need a digit after the E + } else { + return false; + } + i++; + } + if (i < chars.length) { + if (chars[i] >= '0' && chars[i] <= '9') { + if (SystemUtils.IS_JAVA_1_6 && hasLeadingPlusSign && !hasDecPoint) { + return false; + } + // no type qualifier, OK + return true; + } + if (chars[i] == 'e' || chars[i] == 'E') { + // can't have an E at the last byte + return false; + } + if (chars[i] == '.') { + if (hasDecPoint || hasExp) { + // two decimal points or dec in exponent + return false; + } + // single trailing decimal point after non-exponent is ok + return foundDigit; + } + if (!allowSigns + && (chars[i] == 'd' + || chars[i] == 'D' + || chars[i] == 'f' + || chars[i] == 'F')) { + return foundDigit; + } + if (chars[i] == 'l' + || chars[i] == 'L') { + // not allowing L with an exponent or decimal point + return foundDigit && !hasExp && !hasDecPoint; + } + // last character is illegal + return false; + } + // allowSigns is true iff the val ends in 'E' + // found digit it to make sure weird stuff like '.' and '1E-' doesn't pass + return !allowSigns && foundDigit; + } + + /** + *

Checks whether the given String is a parsable number.

+ * + *

Parsable numbers include those Strings understood by {@link Integer#parseInt(String)}, + * {@link Long#parseLong(String)}, {@link Float#parseFloat(String)} or + * {@link Double#parseDouble(String)}. This method can be used instead of catching {@link java.text.ParseException} + * when calling one of those methods.

+ * + *

Hexadecimal and scientific notations are not considered parsable. + * See {@link #isCreatable(String)} on those cases.

+ * + *

{@code Null} and empty String will return false.

+ * + * @param str the String to check. + * @return {@code true} if the string is a parsable number. + * @since 3.4 + */ + public static boolean isParsable(final String str) { + if (StringUtils.isEmpty(str)) { + return false; + } + if (str.charAt(str.length() - 1) == '.') { + return false; + } + if (str.charAt(0) == '-') { + if (str.length() == 1) { + return false; + } + return withDecimalsParsing(str, 1); + } else { + return withDecimalsParsing(str, 0); + } + } + + private static boolean withDecimalsParsing(final String str, final int beginIdx) { + int decimalPoints = 0; + for (int i = beginIdx; i < str.length(); i++) { + final boolean isDecimalPoint = str.charAt(i) == '.'; + if (isDecimalPoint) { + decimalPoints++; + } + if (decimalPoints > 1) { + return false; + } + if (!isDecimalPoint && !Character.isDigit(str.charAt(i))) { + return false; + } + } + return true; + } + + /** + *

Compares two {@code int} values numerically. This is the same functionality as provided in Java 7.

+ * + * @param x the first {@code int} to compare + * @param y the second {@code int} 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(int x, int y) { + if (x == y) { + return 0; + } + return x < y ? -1 : 1; + } + + /** + *

Compares to {@code long} values numerically. This is the same functionality as provided in Java 7.

+ * + * @param x the first {@code long} to compare + * @param y the second {@code long} 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(long x, long y) { + if (x == y) { + return 0; + } + return x < y ? -1 : 1; + } + + /** + *

Compares to {@code short} values numerically. This is the same functionality as provided in Java 7.

+ * + * @param x the first {@code short} to compare + * @param y the second {@code short} 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(short x, short y) { + if (x == y) { + return 0; + } + return x < y ? -1 : 1; + } + + /** + *

Compares two {@code byte} values numerically. This is the same functionality as provided in Java 7.

+ * + * @param x the first {@code byte} to compare + * @param y the second {@code byte} 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(byte x, byte y) { + return x - y; + } +} diff --git a/Java/commons-lang-NumberUtils_657/metadata.json b/Java/commons-lang-NumberUtils_657/metadata.json new file mode 100644 index 000000000..a86c237c4 --- /dev/null +++ b/Java/commons-lang-NumberUtils_657/metadata.json @@ -0,0 +1,21 @@ +{ + "language": "java", + "id": "commons-lang-NumberUtils_657", + "buggyPath": ".", + "referencePath": null, + "buildCommand": "mvn package -V -B -Denforcer.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true -Drat.skip=true -Dlicense.skip=true -Dfindbugs.skip=true -Dgpg.skip=true -Dskip.npm=true -Dskip.gulp=true -Dskip.bower=true -Drat.numUnapprovedLicenses=100 -DskipTests=true -DskipITs=true -Dtest=None -DfailIfNoTests=false", + "testCommand": "mvn test -V -B -Denforcer.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true -Drat.skip=true -Dlicense.skip=true -Dfindbugs.skip=true -Dgpg.skip=true -Dskip.npm=true -Dskip.gulp=true -Dskip.bower=true -Drat.numUnapprovedLicenses=100", + "categories": [ + "safety", + "npe" + ], + "npe": { + "filepath": "src/main/java/org/apache/commons/lang3/math/NumberUtils.java", + "line": 668, + "npe_method": "isAllZeros", + "deref_field": "str", + "npe_class": "NumberUtils", + "repo": "commons-lang", + "bug_id": "NumberUtils_657" + } +} diff --git a/Java/commons-lang-NumberUtils_657/npe.json b/Java/commons-lang-NumberUtils_657/npe.json new file mode 100644 index 000000000..23187e5a9 --- /dev/null +++ b/Java/commons-lang-NumberUtils_657/npe.json @@ -0,0 +1,7 @@ +{ + "filepath": "src/main/java/org/apache/commons/lang3/math/NumberUtils.java", + "line": 668, + "npe_method": "isAllZeros", + "deref_field": "str", + "npe_class": "NumberUtils" +} \ No newline at end of file diff --git a/Java/commons-lang-NumberUtils_679/Dockerfile b/Java/commons-lang-NumberUtils_679/Dockerfile new file mode 100644 index 000000000..7b7fbe349 --- /dev/null +++ b/Java/commons-lang-NumberUtils_679/Dockerfile @@ -0,0 +1,18 @@ +FROM ghcr.io/kupl/starlab-benchmarks/java-base:commons-lang + +ENV TZ=Asia/Seoul + +COPY ./metadata.json . +COPY ./npe.json . +COPY ./buggy.java /tmp/buggy.java +RUN export BUGGY_PATH=$(cat metadata.json | jq -r ".npe.filepath") \ + && export BUGGY_LINE=$(cat metadata.json | jq -r ".npe.line") \ + && export BUGGY_MTHD=$(cat metadata.json | jq -r ".npe.npe_method") \ + && mv /tmp/buggy.java $BUGGY_PATH \ + && echo "[{\"filepath\": \"$BUGGY_PATH\", \"line\": $BUGGY_LINE, \"method_name\": \"$BUGGY_MTHD\"}]" | jq . > traces.json + +RUN git init . && git add -A + +RUN $(cat metadata.json | jq -r ".buildCommand") + +RUN $(cat metadata.json | jq -r ".testCommand"); if [ $? -eq 0 ]; then exit 1; fi diff --git a/Java/commons-lang-NumberUtils_679/buggy.java b/Java/commons-lang-NumberUtils_679/buggy.java new file mode 100644 index 000000000..ae6caafe1 --- /dev/null +++ b/Java/commons-lang-NumberUtils_679/buggy.java @@ -0,0 +1,1645 @@ +/* + * 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 java.lang.reflect.Array; +import java.math.BigDecimal; +import java.math.BigInteger; + +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.SystemUtils; +import org.apache.commons.lang3.Validate; + +/** + *

Provides extra functionality for Java Number classes.

+ * + * @since 2.0 + */ +public class NumberUtils { + + /** Reusable Long constant for zero. */ + public static final Long LONG_ZERO = Long.valueOf(0L); + /** Reusable Long constant for one. */ + public static final Long LONG_ONE = Long.valueOf(1L); + /** Reusable Long constant for minus one. */ + public static final Long LONG_MINUS_ONE = Long.valueOf(-1L); + /** Reusable Integer constant for zero. */ + public static final Integer INTEGER_ZERO = Integer.valueOf(0); + /** Reusable Integer constant for one. */ + public static final Integer INTEGER_ONE = Integer.valueOf(1); + /** Reusable Integer constant for minus one. */ + public static final Integer INTEGER_MINUS_ONE = Integer.valueOf(-1); + /** Reusable Short constant for zero. */ + public static final Short SHORT_ZERO = Short.valueOf((short) 0); + /** Reusable Short constant for one. */ + public static final Short SHORT_ONE = Short.valueOf((short) 1); + /** Reusable Short constant for minus one. */ + public static final Short SHORT_MINUS_ONE = Short.valueOf((short) -1); + /** Reusable Byte constant for zero. */ + public static final Byte BYTE_ZERO = Byte.valueOf((byte) 0); + /** Reusable Byte constant for one. */ + public static final Byte BYTE_ONE = Byte.valueOf((byte) 1); + /** Reusable Byte constant for minus one. */ + public static final Byte BYTE_MINUS_ONE = Byte.valueOf((byte) -1); + /** Reusable Double constant for zero. */ + public static final Double DOUBLE_ZERO = Double.valueOf(0.0d); + /** Reusable Double constant for one. */ + public static final Double DOUBLE_ONE = Double.valueOf(1.0d); + /** Reusable Double constant for minus one. */ + public static final Double DOUBLE_MINUS_ONE = Double.valueOf(-1.0d); + /** Reusable Float constant for zero. */ + public static final Float FLOAT_ZERO = Float.valueOf(0.0f); + /** Reusable Float constant for one. */ + public static final Float FLOAT_ONE = Float.valueOf(1.0f); + /** Reusable Float constant for minus one. */ + public static final Float FLOAT_MINUS_ONE = Float.valueOf(-1.0f); + + /** + *

NumberUtils instances should NOT be constructed in standard programming. + * Instead, the class should be used as NumberUtils.toInt("6");.

+ * + *

This constructor is public to permit tools that require a JavaBean instance + * to operate.

+ */ + public NumberUtils() { + super(); + } + + //----------------------------------------------------------------------- + /** + *

Convert a String to an int, returning + * zero if the conversion fails.

+ * + *

If the string is null, zero is returned.

+ * + *
+     *   NumberUtils.toInt(null) = 0
+     *   NumberUtils.toInt("")   = 0
+     *   NumberUtils.toInt("1")  = 1
+     * 
+ * + * @param str the string to convert, may be null + * @return the int represented by the string, or zero if + * conversion fails + * @since 2.1 + */ + public static int toInt(final String str) { + return toInt(str, 0); + } + + /** + *

Convert a String to an int, returning a + * default value if the conversion fails.

+ * + *

If the string is null, the default value is returned.

+ * + *
+     *   NumberUtils.toInt(null, 1) = 1
+     *   NumberUtils.toInt("", 1)   = 1
+     *   NumberUtils.toInt("1", 0)  = 1
+     * 
+ * + * @param str the string to convert, may be null + * @param defaultValue the default value + * @return the int represented by the string, or the default if conversion fails + * @since 2.1 + */ + public static int toInt(final String str, final int defaultValue) { + if(str == null) { + return defaultValue; + } + try { + return Integer.parseInt(str); + } catch (final NumberFormatException nfe) { + return defaultValue; + } + } + + /** + *

Convert a String to a long, returning + * zero if the conversion fails.

+ * + *

If the string is null, zero is returned.

+ * + *
+     *   NumberUtils.toLong(null) = 0L
+     *   NumberUtils.toLong("")   = 0L
+     *   NumberUtils.toLong("1")  = 1L
+     * 
+ * + * @param str the string to convert, may be null + * @return the long represented by the string, or 0 if + * conversion fails + * @since 2.1 + */ + public static long toLong(final String str) { + return toLong(str, 0L); + } + + /** + *

Convert a String to a long, returning a + * default value if the conversion fails.

+ * + *

If the string is null, the default value is returned.

+ * + *
+     *   NumberUtils.toLong(null, 1L) = 1L
+     *   NumberUtils.toLong("", 1L)   = 1L
+     *   NumberUtils.toLong("1", 0L)  = 1L
+     * 
+ * + * @param str the string to convert, may be null + * @param defaultValue the default value + * @return the long represented by the string, or the default if conversion fails + * @since 2.1 + */ + public static long toLong(final String str, final long defaultValue) { + if (str == null) { + return defaultValue; + } + try { + return Long.parseLong(str); + } catch (final NumberFormatException nfe) { + return defaultValue; + } + } + + /** + *

Convert a String to a float, returning + * 0.0f if the conversion fails.

+ * + *

If the string str is null, + * 0.0f is returned.

+ * + *
+     *   NumberUtils.toFloat(null)   = 0.0f
+     *   NumberUtils.toFloat("")     = 0.0f
+     *   NumberUtils.toFloat("1.5")  = 1.5f
+     * 
+ * + * @param str the string to convert, may be null + * @return the float represented by the string, or 0.0f + * if conversion fails + * @since 2.1 + */ + public static float toFloat(final String str) { + return toFloat(str, 0.0f); + } + + /** + *

Convert a String to a float, returning a + * default value if the conversion fails.

+ * + *

If the string str is null, the default + * value is returned.

+ * + *
+     *   NumberUtils.toFloat(null, 1.1f)   = 1.0f
+     *   NumberUtils.toFloat("", 1.1f)     = 1.1f
+     *   NumberUtils.toFloat("1.5", 0.0f)  = 1.5f
+     * 
+ * + * @param str the string to convert, may be null + * @param defaultValue the default value + * @return the float represented by the string, or defaultValue + * if conversion fails + * @since 2.1 + */ + public static float toFloat(final String str, final float defaultValue) { + if (str == null) { + return defaultValue; + } + try { + return Float.parseFloat(str); + } catch (final NumberFormatException nfe) { + return defaultValue; + } + } + + /** + *

Convert a String to a double, returning + * 0.0d if the conversion fails.

+ * + *

If the string str is null, + * 0.0d is returned.

+ * + *
+     *   NumberUtils.toDouble(null)   = 0.0d
+     *   NumberUtils.toDouble("")     = 0.0d
+     *   NumberUtils.toDouble("1.5")  = 1.5d
+     * 
+ * + * @param str the string to convert, may be null + * @return the double represented by the string, or 0.0d + * if conversion fails + * @since 2.1 + */ + public static double toDouble(final String str) { + return toDouble(str, 0.0d); + } + + /** + *

Convert a String to a double, returning a + * default value if the conversion fails.

+ * + *

If the string str is null, the default + * value is returned.

+ * + *
+     *   NumberUtils.toDouble(null, 1.1d)   = 1.1d
+     *   NumberUtils.toDouble("", 1.1d)     = 1.1d
+     *   NumberUtils.toDouble("1.5", 0.0d)  = 1.5d
+     * 
+ * + * @param str the string to convert, may be null + * @param defaultValue the default value + * @return the double represented by the string, or defaultValue + * if conversion fails + * @since 2.1 + */ + public static double toDouble(final String str, final double defaultValue) { + if (str == null) { + return defaultValue; + } + try { + return Double.parseDouble(str); + } catch (final NumberFormatException nfe) { + return defaultValue; + } + } + + //----------------------------------------------------------------------- + /** + *

Convert a String to a byte, returning + * zero if the conversion fails.

+ * + *

If the string is null, zero is returned.

+ * + *
+     *   NumberUtils.toByte(null) = 0
+     *   NumberUtils.toByte("")   = 0
+     *   NumberUtils.toByte("1")  = 1
+     * 
+ * + * @param str the string to convert, may be null + * @return the byte represented by the string, or zero if + * conversion fails + * @since 2.5 + */ + public static byte toByte(final String str) { + return toByte(str, (byte) 0); + } + + /** + *

Convert a String to a byte, returning a + * default value if the conversion fails.

+ * + *

If the string is null, the default value is returned.

+ * + *
+     *   NumberUtils.toByte(null, 1) = 1
+     *   NumberUtils.toByte("", 1)   = 1
+     *   NumberUtils.toByte("1", 0)  = 1
+     * 
+ * + * @param str the string to convert, may be null + * @param defaultValue the default value + * @return the byte represented by the string, or the default if conversion fails + * @since 2.5 + */ + public static byte toByte(final String str, final byte defaultValue) { + if(str == null) { + return defaultValue; + } + try { + return Byte.parseByte(str); + } catch (final NumberFormatException nfe) { + return defaultValue; + } + } + + /** + *

Convert a String to a short, returning + * zero if the conversion fails.

+ * + *

If the string is null, zero is returned.

+ * + *
+     *   NumberUtils.toShort(null) = 0
+     *   NumberUtils.toShort("")   = 0
+     *   NumberUtils.toShort("1")  = 1
+     * 
+ * + * @param str the string to convert, may be null + * @return the short represented by the string, or zero if + * conversion fails + * @since 2.5 + */ + public static short toShort(final String str) { + return toShort(str, (short) 0); + } + + /** + *

Convert a String to an short, returning a + * default value if the conversion fails.

+ * + *

If the string is null, the default value is returned.

+ * + *
+     *   NumberUtils.toShort(null, 1) = 1
+     *   NumberUtils.toShort("", 1)   = 1
+     *   NumberUtils.toShort("1", 0)  = 1
+     * 
+ * + * @param str the string to convert, may be null + * @param defaultValue the default value + * @return the short represented by the string, or the default if conversion fails + * @since 2.5 + */ + public static short toShort(final String str, final short defaultValue) { + if(str == null) { + return defaultValue; + } + try { + return Short.parseShort(str); + } catch (final NumberFormatException nfe) { + return defaultValue; + } + } + + //----------------------------------------------------------------------- + // must handle Long, Float, Integer, Float, Short, + // BigDecimal, BigInteger and Byte + // useful methods: + // Byte.decode(String) + // Byte.valueOf(String,int radix) + // Byte.valueOf(String) + // Double.valueOf(String) + // Float.valueOf(String) + // Float.valueOf(String) + // Integer.valueOf(String,int radix) + // Integer.valueOf(String) + // Integer.decode(String) + // Integer.getInteger(String) + // Integer.getInteger(String,int val) + // Integer.getInteger(String,Integer val) + // Integer.valueOf(String) + // Double.valueOf(String) + // new Byte(String) + // Long.valueOf(String) + // Long.getLong(String) + // Long.getLong(String,int) + // Long.getLong(String,Integer) + // Long.valueOf(String,int) + // Long.valueOf(String) + // Short.valueOf(String) + // Short.decode(String) + // Short.valueOf(String,int) + // Short.valueOf(String) + // new BigDecimal(String) + // new BigInteger(String) + // new BigInteger(String,int radix) + // Possible inputs: + // 45 45.5 45E7 4.5E7 Hex Oct Binary xxxF xxxD xxxf xxxd + // plus minus everything. Prolly more. A lot are not separable. + + /** + *

Turns a string value into a java.lang.Number.

+ * + *

If the string starts with {@code 0x} or {@code -0x} (lower or upper case) or {@code #} or {@code -#}, it + * will be interpreted as a hexadecimal Integer - or Long, if the number of digits after the + * prefix is more than 8 - or BigInteger if there are more than 16 digits. + *

+ *

Then, the value is examined for a type qualifier on the end, i.e. one of + * 'f','F','d','D','l','L'. If it is found, it starts + * trying to create successively larger types from the type specified + * until one is found that can represent the value.

+ * + *

If a type specifier is not found, it will check for a decimal point + * and then try successively larger types from Integer to + * BigInteger and from Float to + * BigDecimal.

+ * + *

+ * Integral values with a leading {@code 0} will be interpreted as octal; the returned number will + * be Integer, Long or BigDecimal as appropriate. + *

+ * + *

Returns null if the string is null.

+ * + *

This method does not trim the input string, i.e., strings with leading + * or trailing spaces will generate NumberFormatExceptions.

+ * + * @param str String containing a number, may be null + * @return Number created from the string (or null if the input is null) + * @throws NumberFormatException if the value cannot be converted + */ + public static Number createNumber(final String str) throws NumberFormatException { + if (str == null) { + return null; + } + if (StringUtils.isBlank(str)) { + throw new NumberFormatException("A blank string is not a valid number"); + } + // Need to deal with all possible hex prefixes here + final String[] hex_prefixes = {"0x", "0X", "-0x", "-0X", "#", "-#"}; + int pfxLen = 0; + for(final String pfx : hex_prefixes) { + if (str.startsWith(pfx)) { + pfxLen += pfx.length(); + break; + } + } + if (pfxLen > 0) { // we have a hex number + char firstSigDigit = 0; // strip leading zeroes + for(int i = pfxLen; i < str.length(); i++) { + firstSigDigit = str.charAt(i); + if (firstSigDigit == '0') { // count leading zeroes + pfxLen++; + } else { + break; + } + } + final int hexDigits = str.length() - pfxLen; + if (hexDigits > 16 || hexDigits == 16 && firstSigDigit > '7') { // too many for Long + return createBigInteger(str); + } + if (hexDigits > 8 || hexDigits == 8 && firstSigDigit > '7') { // too many for an int + return createLong(str); + } + return createInteger(str); + } + final char lastChar = str.charAt(str.length() - 1); + String mant; + String dec; + String exp; + final int decPos = str.indexOf('.'); + final int expPos = str.indexOf('e') + str.indexOf('E') + 1; // assumes both not present + // if both e and E are present, this is caught by the checks on expPos (which prevent IOOBE) + // and the parsing which will detect if e or E appear in a number due to using the wrong offset + + if (decPos > -1) { // there is a decimal point + if (expPos > -1) { // there is an exponent + if (expPos < decPos || expPos > str.length()) { // prevents double exponent causing IOOBE + throw new NumberFormatException(str + " is not a valid number."); + } + dec = str.substring(decPos + 1, expPos); + } else { + dec = str.substring(decPos + 1); + } + mant = getMantissa(str, decPos); + } else { + if (expPos > -1) { + if (expPos > str.length()) { // prevents double exponent causing IOOBE + throw new NumberFormatException(str + " is not a valid number."); + } + mant = getMantissa(str, expPos); + } else { + mant = getMantissa(str); + } + dec = null; + } + if (!Character.isDigit(lastChar) && lastChar != '.') { + if (expPos > -1 && expPos < str.length() - 1) { + exp = str.substring(expPos + 1, str.length() - 1); + } else { + exp = null; + } + //Requesting a specific type.. + final String numeric = str.substring(0, str.length() - 1); + final boolean allZeros = isAllZeros(mant) && isAllZeros(exp); + switch (lastChar) { + case 'l' : + case 'L' : + if (dec == null + && exp == null + && (numeric.charAt(0) == '-' && isDigits(numeric.substring(1)) || isDigits(numeric))) { + try { + return createLong(numeric); + } catch (final NumberFormatException nfe) { // NOPMD + // Too big for a long + } + return createBigInteger(numeric); + + } + throw new NumberFormatException(str + " is not a valid number."); + case 'f' : + case 'F' : + try { + final Float f = NumberUtils.createFloat(str); + if (!(f.isInfinite() || f.floatValue() == 0.0F && !allZeros)) { + //If it's too big for a float or the float value = 0 and the string + //has non-zeros in it, then float does not have the precision we want + return f; + } + + } catch (final NumberFormatException nfe) { // NOPMD + // ignore the bad number + } + //$FALL-THROUGH$ + case 'd' : + case 'D' : + try { + final Double d = NumberUtils.createDouble(str); + if (!(d.isInfinite() || d.floatValue() == 0.0D && !allZeros)) { + return d; + } + } catch (final NumberFormatException nfe) { // NOPMD + // ignore the bad number + } + try { + return createBigDecimal(numeric); + } catch (final NumberFormatException e) { // NOPMD + // ignore the bad number + } + //$FALL-THROUGH$ + default : + throw new NumberFormatException(str + " is not a valid number."); + + } + } + //User doesn't have a preference on the return type, so let's start + //small and go from there... + if (expPos > -1 && expPos < str.length() - 1) { + exp = str.substring(expPos + 1, str.length()); + } else { + exp = null; + } + if (dec == null && exp == null) { // no decimal point and no exponent + //Must be an Integer, Long, Biginteger + try { + return createInteger(str); + } catch (final NumberFormatException nfe) { // NOPMD + // ignore the bad number + } + try { + return createLong(str); + } catch (final NumberFormatException nfe) { // NOPMD + // ignore the bad number + } + return createBigInteger(str); + } + + //Must be a Float, Double, BigDecimal + final boolean allZeros = isAllZeros(mant) && isAllZeros(exp); + try { + final Float f = createFloat(str); + final Double d = createDouble(str); + if (!f.isInfinite() + && !(f.floatValue() == 0.0F && !allZeros) + && f.toString().equals(d.toString())) { + return f; + } + if (!d.isInfinite() && !(d.doubleValue() == 0.0D && !allZeros)) { + final BigDecimal b = createBigDecimal(str); + if (b.compareTo(BigDecimal.valueOf(d)) == 0) { + return d; + } + return b; + } + } catch (final NumberFormatException nfe) { // NOPMD + // ignore the bad number + } + return createBigDecimal(str); + } + + /** + *

Utility method for {@link #createNumber(java.lang.String)}.

+ * + *

Returns mantissa of the given number.

+ * + * @param str the string representation of the number + * @return mantissa of the given number + */ + private static String getMantissa(final String str) { + return getMantissa(str, str.length()); + } + + /** + *

Utility method for {@link #createNumber(java.lang.String)}.

+ * + *

Returns mantissa of the given number.

+ * + * @param str the string representation of the number + * @param stopPos the position of the exponent or decimal point + * @return mantissa of the given number + */ + private static String getMantissa(final String str, final int stopPos) { + final char firstChar = str.charAt(0); + final boolean hasSign = firstChar == '-' || firstChar == '+'; + + return hasSign ? str.substring(1, stopPos) : str.substring(0, stopPos); + } + + /** + *

Utility method for {@link #createNumber(java.lang.String)}.

+ * + *

Returns true if s is null.

+ * + * @param str the String to check + * @return if it is all zeros or null + */ + private static boolean isAllZeros(final String str) { + if (str == null) { + return true; + } + for (int i = str.length() - 1; i >= 0; i--) { + if (str.charAt(i) != '0') { + return false; + } + } + return str.length() > 0; + } + + //----------------------------------------------------------------------- + /** + *

Convert a String to a Float.

+ * + *

Returns null if the string is null.

+ * + * @param str a String to convert, may be null + * @return converted Float (or null if the input is null) + * @throws NumberFormatException if the value cannot be converted + */ +// ----------------------------------------------------------------------- +/** + *

Convert a String to a Float.

+ * + *

Returns null if the string is null.

+ * + * @param str + * a String to convert, may be null + * @return converted Float (or null if the input is null) + * @throws NumberFormatException + * if the value cannot be converted + */ +public static java.lang.Float createFloat(final java.lang.String str) { + { + return java.lang.Float.valueOf(/* NPEX_NULL_EXP */ + str); + } +} + + /** + *

Convert a String to a Double.

+ * + *

Returns null if the string is null.

+ * + * @param str a String to convert, may be null + * @return converted Double (or null if the input is null) + * @throws NumberFormatException if the value cannot be converted + */ + public static Double createDouble(final String str) { + if (str == null) { + return null; + } + return Double.valueOf(str); + } + + /** + *

Convert a String to a Integer, handling + * hex (0xhhhh) and octal (0dddd) notations. + * N.B. a leading zero means octal; spaces are not trimmed.

+ * + *

Returns null if the string is null.

+ * + * @param str a String to convert, may be null + * @return converted Integer (or null if the input is null) + * @throws NumberFormatException if the value cannot be converted + */ + public static Integer createInteger(final String str) { + if (str == null) { + return null; + } + // decode() handles 0xAABD and 0777 (hex and octal) as well. + return Integer.decode(str); + } + + /** + *

Convert a String to a Long; + * since 3.1 it handles hex (0Xhhhh) and octal (0ddd) notations. + * N.B. a leading zero means octal; spaces are not trimmed.

+ * + *

Returns null if the string is null.

+ * + * @param str a String to convert, may be null + * @return converted Long (or null if the input is null) + * @throws NumberFormatException if the value cannot be converted + */ + public static Long createLong(final String str) { + if (str == null) { + return null; + } + return Long.decode(str); + } + + /** + *

Convert a String to a BigInteger; + * since 3.2 it handles hex (0x or #) and octal (0) notations.

+ * + *

Returns null if the string is null.

+ * + * @param str a String to convert, may be null + * @return converted BigInteger (or null if the input is null) + * @throws NumberFormatException if the value cannot be converted + */ + public static BigInteger createBigInteger(final String str) { + if (str == null) { + return null; + } + int pos = 0; // offset within string + int radix = 10; + boolean negate = false; // need to negate later? + if (str.startsWith("-")) { + negate = true; + pos = 1; + } + if (str.startsWith("0x", pos) || str.startsWith("0X", pos)) { // hex + radix = 16; + pos += 2; + } else if (str.startsWith("#", pos)) { // alternative hex (allowed by Long/Integer) + radix = 16; + pos ++; + } else if (str.startsWith("0", pos) && str.length() > pos + 1) { // octal; so long as there are additional digits + radix = 8; + pos ++; + } // default is to treat as decimal + + final BigInteger value = new BigInteger(str.substring(pos), radix); + return negate ? value.negate() : value; + } + + /** + *

Convert a String to a BigDecimal.

+ * + *

Returns null if the string is null.

+ * + * @param str a String to convert, may be null + * @return converted BigDecimal (or null if the input is null) + * @throws NumberFormatException if the value cannot be converted + */ + public static BigDecimal createBigDecimal(final String str) { + if (str == null) { + return null; + } + // handle JDK1.3.1 bug where "" throws IndexOutOfBoundsException + if (StringUtils.isBlank(str)) { + throw new NumberFormatException("A blank string is not a valid number"); + } + if (str.trim().startsWith("--")) { + // this is protection for poorness in java.lang.BigDecimal. + // it accepts this as a legal value, but it does not appear + // to be in specification of class. OS X Java parses it to + // a wrong value. + throw new NumberFormatException(str + " is not a valid number."); + } + return new BigDecimal(str); + } + + // Min in array + //-------------------------------------------------------------------- + /** + *

Returns the minimum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the minimum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @since 3.4 Changed signature from min(long[]) to min(long...) + */ + public static long min(final long... array) { + // Validates input + validateArray(array); + + // Finds and returns min + long min = array[0]; + for (int i = 1; i < array.length; i++) { + if (array[i] < min) { + min = array[i]; + } + } + + return min; + } + + /** + *

Returns the minimum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the minimum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @since 3.4 Changed signature from min(int[]) to min(int...) + */ + public static int min(final int... array) { + // Validates input + validateArray(array); + + // Finds and returns min + int min = array[0]; + for (int j = 1; j < array.length; j++) { + if (array[j] < min) { + min = array[j]; + } + } + + return min; + } + + /** + *

Returns the minimum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the minimum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @since 3.4 Changed signature from min(short[]) to min(short...) + */ + public static short min(final short... array) { + // Validates input + validateArray(array); + + // Finds and returns min + short min = array[0]; + for (int i = 1; i < array.length; i++) { + if (array[i] < min) { + min = array[i]; + } + } + + return min; + } + + /** + *

Returns the minimum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the minimum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @since 3.4 Changed signature from min(byte[]) to min(byte...) + */ + public static byte min(final byte... array) { + // Validates input + validateArray(array); + + // Finds and returns min + byte min = array[0]; + for (int i = 1; i < array.length; i++) { + if (array[i] < min) { + min = array[i]; + } + } + + return min; + } + + /** + *

Returns the minimum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the minimum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @see IEEE754rUtils#min(double[]) IEEE754rUtils for a version of this method that handles NaN differently + * @since 3.4 Changed signature from min(double[]) to min(double...) + */ + public static double min(final double... array) { + // Validates input + validateArray(array); + + // Finds and returns min + double min = array[0]; + for (int i = 1; i < array.length; i++) { + if (Double.isNaN(array[i])) { + return Double.NaN; + } + if (array[i] < min) { + min = array[i]; + } + } + + return min; + } + + /** + *

Returns the minimum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the minimum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @see IEEE754rUtils#min(float[]) IEEE754rUtils for a version of this method that handles NaN differently + * @since 3.4 Changed signature from min(float[]) to min(float...) + */ + public static float min(final float... array) { + // Validates input + validateArray(array); + + // Finds and returns min + float min = array[0]; + for (int i = 1; i < array.length; i++) { + if (Float.isNaN(array[i])) { + return Float.NaN; + } + if (array[i] < min) { + min = array[i]; + } + } + + return min; + } + + // Max in array + //-------------------------------------------------------------------- + /** + *

Returns the maximum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the maximum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @since 3.4 Changed signature from max(long[]) to max(long...) + */ + public static long max(final long... array) { + // Validates input + validateArray(array); + + // Finds and returns max + long max = array[0]; + for (int j = 1; j < array.length; j++) { + if (array[j] > max) { + max = array[j]; + } + } + + return max; + } + + /** + *

Returns the maximum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the maximum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @since 3.4 Changed signature from max(int[]) to max(int...) + */ + public static int max(final int... array) { + // Validates input + validateArray(array); + + // Finds and returns max + int max = array[0]; + for (int j = 1; j < array.length; j++) { + if (array[j] > max) { + max = array[j]; + } + } + + return max; + } + + /** + *

Returns the maximum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the maximum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @since 3.4 Changed signature from max(short[]) to max(short...) + */ + public static short max(final short... array) { + // Validates input + validateArray(array); + + // Finds and returns max + short max = array[0]; + for (int i = 1; i < array.length; i++) { + if (array[i] > max) { + max = array[i]; + } + } + + return max; + } + + /** + *

Returns the maximum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the maximum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @since 3.4 Changed signature from max(byte[]) to max(byte...) + */ + public static byte max(final byte... array) { + // Validates input + validateArray(array); + + // Finds and returns max + byte max = array[0]; + for (int i = 1; i < array.length; i++) { + if (array[i] > max) { + max = array[i]; + } + } + + return max; + } + + /** + *

Returns the maximum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the maximum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @see IEEE754rUtils#max(double[]) IEEE754rUtils for a version of this method that handles NaN differently + * @since 3.4 Changed signature from max(double[]) to max(double...) + */ + public static double max(final double... array) { + // Validates input + validateArray(array); + + // Finds and returns max + double max = array[0]; + for (int j = 1; j < array.length; j++) { + if (Double.isNaN(array[j])) { + return Double.NaN; + } + if (array[j] > max) { + max = array[j]; + } + } + + return max; + } + + /** + *

Returns the maximum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the maximum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @see IEEE754rUtils#max(float[]) IEEE754rUtils for a version of this method that handles NaN differently + * @since 3.4 Changed signature from max(float[]) to max(float...) + */ + public static float max(final float... array) { + // Validates input + validateArray(array); + + // Finds and returns max + float max = array[0]; + for (int j = 1; j < array.length; j++) { + if (Float.isNaN(array[j])) { + return Float.NaN; + } + if (array[j] > max) { + max = array[j]; + } + } + + return max; + } + + /** + * Checks if the specified array is neither null nor empty. + * + * @param array the array to check + * @throws IllegalArgumentException if {@code array} is either {@code null} or empty + */ + private static void validateArray(final Object array) { + if (array == null) { + throw new IllegalArgumentException("The Array must not be null"); + } + Validate.isTrue(Array.getLength(array) != 0, "Array cannot be empty."); + } + + // 3 param min + //----------------------------------------------------------------------- + /** + *

Gets the minimum of three long values.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the smallest of the values + */ + public static long min(long a, final long b, final long c) { + if (b < a) { + a = b; + } + if (c < a) { + a = c; + } + return a; + } + + /** + *

Gets the minimum of three int values.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the smallest of the values + */ + public static int min(int a, final int b, final int c) { + if (b < a) { + a = b; + } + if (c < a) { + a = c; + } + return a; + } + + /** + *

Gets the minimum of three short values.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the smallest of the values + */ + public static short min(short a, final short b, final short c) { + if (b < a) { + a = b; + } + if (c < a) { + a = c; + } + return a; + } + + /** + *

Gets the minimum of three byte values.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the smallest of the values + */ + public static byte min(byte a, final byte b, final byte c) { + if (b < a) { + a = b; + } + if (c < a) { + a = c; + } + return a; + } + + /** + *

Gets the minimum of three double values.

+ * + *

If any value is NaN, NaN is + * returned. Infinity is handled.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the smallest of the values + * @see IEEE754rUtils#min(double, double, double) for a version of this method that handles NaN differently + */ + public static double min(final double a, final double b, final double c) { + return Math.min(Math.min(a, b), c); + } + + /** + *

Gets the minimum of three float values.

+ * + *

If any value is NaN, NaN is + * returned. Infinity is handled.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the smallest of the values + * @see IEEE754rUtils#min(float, float, float) for a version of this method that handles NaN differently + */ + public static float min(final float a, final float b, final float c) { + return Math.min(Math.min(a, b), c); + } + + // 3 param max + //----------------------------------------------------------------------- + /** + *

Gets the maximum of three long values.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the largest of the values + */ + public static long max(long a, final long b, final long c) { + if (b > a) { + a = b; + } + if (c > a) { + a = c; + } + return a; + } + + /** + *

Gets the maximum of three int values.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the largest of the values + */ + public static int max(int a, final int b, final int c) { + if (b > a) { + a = b; + } + if (c > a) { + a = c; + } + return a; + } + + /** + *

Gets the maximum of three short values.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the largest of the values + */ + public static short max(short a, final short b, final short c) { + if (b > a) { + a = b; + } + if (c > a) { + a = c; + } + return a; + } + + /** + *

Gets the maximum of three byte values.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the largest of the values + */ + public static byte max(byte a, final byte b, final byte c) { + if (b > a) { + a = b; + } + if (c > a) { + a = c; + } + return a; + } + + /** + *

Gets the maximum of three double values.

+ * + *

If any value is NaN, NaN is + * returned. Infinity is handled.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the largest of the values + * @see IEEE754rUtils#max(double, double, double) for a version of this method that handles NaN differently + */ + public static double max(final double a, final double b, final double c) { + return Math.max(Math.max(a, b), c); + } + + /** + *

Gets the maximum of three float values.

+ * + *

If any value is NaN, NaN is + * returned. Infinity is handled.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the largest of the values + * @see IEEE754rUtils#max(float, float, float) for a version of this method that handles NaN differently + */ + public static float max(final float a, final float b, final float c) { + return Math.max(Math.max(a, b), c); + } + + //----------------------------------------------------------------------- + /** + *

Checks whether the String contains only + * digit characters.

+ * + *

Null and empty String will return + * false.

+ * + * @param str the String to check + * @return true if str contains only Unicode numeric + */ + public static boolean isDigits(final String str) { + return StringUtils.isNumeric(str); + } + + /** + *

Checks whether the String a valid Java number.

+ * + *

Valid numbers include hexadecimal marked with the 0x or + * 0X qualifier, octal numbers, scientific notation and + * numbers marked with a type qualifier (e.g. 123L).

+ * + *

Non-hexadecimal strings beginning with a leading zero are + * treated as octal values. Thus the string 09 will return + * false, since 9 is not a valid octal value. + * However, numbers beginning with {@code 0.} are treated as decimal.

+ * + *

null and empty/blank {@code String} will return + * false.

+ * + *

Note, {@link #createNumber(String)} should return a number for every + * input resuling in true.

+ * + * @param str the String to check + * @return true if the string is a correctly formatted number + * @since 3.3 the code supports hex {@code 0Xhhh} an + * octal {@code 0ddd} validation + * @deprecated This feature will be removed in Lang 4.0, + * use {@link NumberUtils#isCreatable(String)} instead + */ + @Deprecated + public static boolean isNumber(final String str) { + return isCreatable(str); + } + + /** + *

Checks whether the String a valid Java number.

+ * + *

Valid numbers include hexadecimal marked with the 0x or + * 0X qualifier, octal numbers, scientific notation and + * numbers marked with a type qualifier (e.g. 123L).

+ * + *

Non-hexadecimal strings beginning with a leading zero are + * treated as octal values. Thus the string 09 will return + * false, since 9 is not a valid octal value. + * However, numbers beginning with {@code 0.} are treated as decimal.

+ * + *

null and empty/blank {@code String} will return + * false.

+ * + *

Note, {@link #createNumber(String)} should return a number for every + * input resuling in true.

+ * + * @param str the String to check + * @return true if the string is a correctly formatted number + * @since 3.5 the code supports the "+" suffix on numbers except for integers in Java 1.6 + */ + public static boolean isCreatable(final String str) { + if (StringUtils.isEmpty(str)) { + return false; + } + final char[] chars = str.toCharArray(); + int sz = chars.length; + boolean hasExp = false; + boolean hasDecPoint = false; + boolean allowSigns = false; + boolean foundDigit = false; + // deal with any possible sign up front + final int start = chars[0] == '-' || chars[0] == '+' ? 1 : 0; + final boolean hasLeadingPlusSign = start == 1 && chars[0] == '+'; + if (sz > start + 1 && chars[start] == '0') { // leading 0 + if (chars[start + 1] == 'x' || chars[start + 1] == 'X') { // leading 0x/0X + int i = start + 2; + if (i == sz) { + return false; // str == "0x" + } + // checking hex (it can't be anything else) + for (; i < chars.length; i++) { + if ((chars[i] < '0' || chars[i] > '9') + && (chars[i] < 'a' || chars[i] > 'f') + && (chars[i] < 'A' || chars[i] > 'F')) { + return false; + } + } + return true; + } else if (Character.isDigit(chars[start + 1])) { + // leading 0, but not hex, must be octal + int i = start + 1; + for (; i < chars.length; i++) { + if (chars[i] < '0' || chars[i] > '7') { + return false; + } + } + return true; + } + } + sz--; // don't want to loop to the last char, check it afterwords + // for type qualifiers + int i = start; + // loop to the next to last char or to the last char if we need another digit to + // make a valid number (e.g. chars[0..5] = "1234E") + while (i < sz || i < sz + 1 && allowSigns && !foundDigit) { + if (chars[i] >= '0' && chars[i] <= '9') { + foundDigit = true; + allowSigns = false; + + } else if (chars[i] == '.') { + if (hasDecPoint || hasExp) { + // two decimal points or dec in exponent + return false; + } + hasDecPoint = true; + } else if (chars[i] == 'e' || chars[i] == 'E') { + // we've already taken care of hex. + if (hasExp) { + // two E's + return false; + } + if (!foundDigit) { + return false; + } + hasExp = true; + allowSigns = true; + } else if (chars[i] == '+' || chars[i] == '-') { + if (!allowSigns) { + return false; + } + allowSigns = false; + foundDigit = false; // we need a digit after the E + } else { + return false; + } + i++; + } + if (i < chars.length) { + if (chars[i] >= '0' && chars[i] <= '9') { + if (SystemUtils.IS_JAVA_1_6 && hasLeadingPlusSign && !hasDecPoint) { + return false; + } + // no type qualifier, OK + return true; + } + if (chars[i] == 'e' || chars[i] == 'E') { + // can't have an E at the last byte + return false; + } + if (chars[i] == '.') { + if (hasDecPoint || hasExp) { + // two decimal points or dec in exponent + return false; + } + // single trailing decimal point after non-exponent is ok + return foundDigit; + } + if (!allowSigns + && (chars[i] == 'd' + || chars[i] == 'D' + || chars[i] == 'f' + || chars[i] == 'F')) { + return foundDigit; + } + if (chars[i] == 'l' + || chars[i] == 'L') { + // not allowing L with an exponent or decimal point + return foundDigit && !hasExp && !hasDecPoint; + } + // last character is illegal + return false; + } + // allowSigns is true iff the val ends in 'E' + // found digit it to make sure weird stuff like '.' and '1E-' doesn't pass + return !allowSigns && foundDigit; + } + + /** + *

Checks whether the given String is a parsable number.

+ * + *

Parsable numbers include those Strings understood by {@link Integer#parseInt(String)}, + * {@link Long#parseLong(String)}, {@link Float#parseFloat(String)} or + * {@link Double#parseDouble(String)}. This method can be used instead of catching {@link java.text.ParseException} + * when calling one of those methods.

+ * + *

Hexadecimal and scientific notations are not considered parsable. + * See {@link #isCreatable(String)} on those cases.

+ * + *

{@code Null} and empty String will return false.

+ * + * @param str the String to check. + * @return {@code true} if the string is a parsable number. + * @since 3.4 + */ + public static boolean isParsable(final String str) { + if (StringUtils.isEmpty(str)) { + return false; + } + if (str.charAt(str.length() - 1) == '.') { + return false; + } + if (str.charAt(0) == '-') { + if (str.length() == 1) { + return false; + } + return withDecimalsParsing(str, 1); + } else { + return withDecimalsParsing(str, 0); + } + } + + private static boolean withDecimalsParsing(final String str, final int beginIdx) { + int decimalPoints = 0; + for (int i = beginIdx; i < str.length(); i++) { + final boolean isDecimalPoint = str.charAt(i) == '.'; + if (isDecimalPoint) { + decimalPoints++; + } + if (decimalPoints > 1) { + return false; + } + if (!isDecimalPoint && !Character.isDigit(str.charAt(i))) { + return false; + } + } + return true; + } + + /** + *

Compares two {@code int} values numerically. This is the same functionality as provided in Java 7.

+ * + * @param x the first {@code int} to compare + * @param y the second {@code int} 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(int x, int y) { + if (x == y) { + return 0; + } + return x < y ? -1 : 1; + } + + /** + *

Compares to {@code long} values numerically. This is the same functionality as provided in Java 7.

+ * + * @param x the first {@code long} to compare + * @param y the second {@code long} 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(long x, long y) { + if (x == y) { + return 0; + } + return x < y ? -1 : 1; + } + + /** + *

Compares to {@code short} values numerically. This is the same functionality as provided in Java 7.

+ * + * @param x the first {@code short} to compare + * @param y the second {@code short} 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(short x, short y) { + if (x == y) { + return 0; + } + return x < y ? -1 : 1; + } + + /** + *

Compares two {@code byte} values numerically. This is the same functionality as provided in Java 7.

+ * + * @param x the first {@code byte} to compare + * @param y the second {@code byte} 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(byte x, byte y) { + return x - y; + } +} diff --git a/Java/commons-lang-NumberUtils_679/metadata.json b/Java/commons-lang-NumberUtils_679/metadata.json new file mode 100644 index 000000000..f593bdea9 --- /dev/null +++ b/Java/commons-lang-NumberUtils_679/metadata.json @@ -0,0 +1,21 @@ +{ + "language": "java", + "id": "commons-lang-NumberUtils_679", + "buggyPath": ".", + "referencePath": null, + "buildCommand": "mvn package -V -B -Denforcer.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true -Drat.skip=true -Dlicense.skip=true -Dfindbugs.skip=true -Dgpg.skip=true -Dskip.npm=true -Dskip.gulp=true -Dskip.bower=true -Drat.numUnapprovedLicenses=100 -DskipTests=true -DskipITs=true -Dtest=None -DfailIfNoTests=false", + "testCommand": "mvn test -V -B -Denforcer.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true -Drat.skip=true -Dlicense.skip=true -Dfindbugs.skip=true -Dgpg.skip=true -Dskip.npm=true -Dskip.gulp=true -Dskip.bower=true -Drat.numUnapprovedLicenses=100", + "categories": [ + "safety", + "npe" + ], + "npe": { + "filepath": "src/main/java/org/apache/commons/lang3/math/NumberUtils.java", + "line": 693, + "npe_method": "createFloat", + "deref_field": "str", + "npe_class": "NumberUtils", + "repo": "commons-lang", + "bug_id": "NumberUtils_679" + } +} diff --git a/Java/commons-lang-NumberUtils_679/npe.json b/Java/commons-lang-NumberUtils_679/npe.json new file mode 100644 index 000000000..d72bc8a74 --- /dev/null +++ b/Java/commons-lang-NumberUtils_679/npe.json @@ -0,0 +1,7 @@ +{ + "filepath": "src/main/java/org/apache/commons/lang3/math/NumberUtils.java", + "line": 693, + "npe_method": "createFloat", + "deref_field": "str", + "npe_class": "NumberUtils" +} \ No newline at end of file diff --git a/Java/commons-lang-NumberUtils_695/Dockerfile b/Java/commons-lang-NumberUtils_695/Dockerfile new file mode 100644 index 000000000..7b7fbe349 --- /dev/null +++ b/Java/commons-lang-NumberUtils_695/Dockerfile @@ -0,0 +1,18 @@ +FROM ghcr.io/kupl/starlab-benchmarks/java-base:commons-lang + +ENV TZ=Asia/Seoul + +COPY ./metadata.json . +COPY ./npe.json . +COPY ./buggy.java /tmp/buggy.java +RUN export BUGGY_PATH=$(cat metadata.json | jq -r ".npe.filepath") \ + && export BUGGY_LINE=$(cat metadata.json | jq -r ".npe.line") \ + && export BUGGY_MTHD=$(cat metadata.json | jq -r ".npe.npe_method") \ + && mv /tmp/buggy.java $BUGGY_PATH \ + && echo "[{\"filepath\": \"$BUGGY_PATH\", \"line\": $BUGGY_LINE, \"method_name\": \"$BUGGY_MTHD\"}]" | jq . > traces.json + +RUN git init . && git add -A + +RUN $(cat metadata.json | jq -r ".buildCommand") + +RUN $(cat metadata.json | jq -r ".testCommand"); if [ $? -eq 0 ]; then exit 1; fi diff --git a/Java/commons-lang-NumberUtils_695/buggy.java b/Java/commons-lang-NumberUtils_695/buggy.java new file mode 100644 index 000000000..109174ed6 --- /dev/null +++ b/Java/commons-lang-NumberUtils_695/buggy.java @@ -0,0 +1,1644 @@ +/* + * 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 java.lang.reflect.Array; +import java.math.BigDecimal; +import java.math.BigInteger; + +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.SystemUtils; +import org.apache.commons.lang3.Validate; + +/** + *

Provides extra functionality for Java Number classes.

+ * + * @since 2.0 + */ +public class NumberUtils { + + /** Reusable Long constant for zero. */ + public static final Long LONG_ZERO = Long.valueOf(0L); + /** Reusable Long constant for one. */ + public static final Long LONG_ONE = Long.valueOf(1L); + /** Reusable Long constant for minus one. */ + public static final Long LONG_MINUS_ONE = Long.valueOf(-1L); + /** Reusable Integer constant for zero. */ + public static final Integer INTEGER_ZERO = Integer.valueOf(0); + /** Reusable Integer constant for one. */ + public static final Integer INTEGER_ONE = Integer.valueOf(1); + /** Reusable Integer constant for minus one. */ + public static final Integer INTEGER_MINUS_ONE = Integer.valueOf(-1); + /** Reusable Short constant for zero. */ + public static final Short SHORT_ZERO = Short.valueOf((short) 0); + /** Reusable Short constant for one. */ + public static final Short SHORT_ONE = Short.valueOf((short) 1); + /** Reusable Short constant for minus one. */ + public static final Short SHORT_MINUS_ONE = Short.valueOf((short) -1); + /** Reusable Byte constant for zero. */ + public static final Byte BYTE_ZERO = Byte.valueOf((byte) 0); + /** Reusable Byte constant for one. */ + public static final Byte BYTE_ONE = Byte.valueOf((byte) 1); + /** Reusable Byte constant for minus one. */ + public static final Byte BYTE_MINUS_ONE = Byte.valueOf((byte) -1); + /** Reusable Double constant for zero. */ + public static final Double DOUBLE_ZERO = Double.valueOf(0.0d); + /** Reusable Double constant for one. */ + public static final Double DOUBLE_ONE = Double.valueOf(1.0d); + /** Reusable Double constant for minus one. */ + public static final Double DOUBLE_MINUS_ONE = Double.valueOf(-1.0d); + /** Reusable Float constant for zero. */ + public static final Float FLOAT_ZERO = Float.valueOf(0.0f); + /** Reusable Float constant for one. */ + public static final Float FLOAT_ONE = Float.valueOf(1.0f); + /** Reusable Float constant for minus one. */ + public static final Float FLOAT_MINUS_ONE = Float.valueOf(-1.0f); + + /** + *

NumberUtils instances should NOT be constructed in standard programming. + * Instead, the class should be used as NumberUtils.toInt("6");.

+ * + *

This constructor is public to permit tools that require a JavaBean instance + * to operate.

+ */ + public NumberUtils() { + super(); + } + + //----------------------------------------------------------------------- + /** + *

Convert a String to an int, returning + * zero if the conversion fails.

+ * + *

If the string is null, zero is returned.

+ * + *
+     *   NumberUtils.toInt(null) = 0
+     *   NumberUtils.toInt("")   = 0
+     *   NumberUtils.toInt("1")  = 1
+     * 
+ * + * @param str the string to convert, may be null + * @return the int represented by the string, or zero if + * conversion fails + * @since 2.1 + */ + public static int toInt(final String str) { + return toInt(str, 0); + } + + /** + *

Convert a String to an int, returning a + * default value if the conversion fails.

+ * + *

If the string is null, the default value is returned.

+ * + *
+     *   NumberUtils.toInt(null, 1) = 1
+     *   NumberUtils.toInt("", 1)   = 1
+     *   NumberUtils.toInt("1", 0)  = 1
+     * 
+ * + * @param str the string to convert, may be null + * @param defaultValue the default value + * @return the int represented by the string, or the default if conversion fails + * @since 2.1 + */ + public static int toInt(final String str, final int defaultValue) { + if(str == null) { + return defaultValue; + } + try { + return Integer.parseInt(str); + } catch (final NumberFormatException nfe) { + return defaultValue; + } + } + + /** + *

Convert a String to a long, returning + * zero if the conversion fails.

+ * + *

If the string is null, zero is returned.

+ * + *
+     *   NumberUtils.toLong(null) = 0L
+     *   NumberUtils.toLong("")   = 0L
+     *   NumberUtils.toLong("1")  = 1L
+     * 
+ * + * @param str the string to convert, may be null + * @return the long represented by the string, or 0 if + * conversion fails + * @since 2.1 + */ + public static long toLong(final String str) { + return toLong(str, 0L); + } + + /** + *

Convert a String to a long, returning a + * default value if the conversion fails.

+ * + *

If the string is null, the default value is returned.

+ * + *
+     *   NumberUtils.toLong(null, 1L) = 1L
+     *   NumberUtils.toLong("", 1L)   = 1L
+     *   NumberUtils.toLong("1", 0L)  = 1L
+     * 
+ * + * @param str the string to convert, may be null + * @param defaultValue the default value + * @return the long represented by the string, or the default if conversion fails + * @since 2.1 + */ + public static long toLong(final String str, final long defaultValue) { + if (str == null) { + return defaultValue; + } + try { + return Long.parseLong(str); + } catch (final NumberFormatException nfe) { + return defaultValue; + } + } + + /** + *

Convert a String to a float, returning + * 0.0f if the conversion fails.

+ * + *

If the string str is null, + * 0.0f is returned.

+ * + *
+     *   NumberUtils.toFloat(null)   = 0.0f
+     *   NumberUtils.toFloat("")     = 0.0f
+     *   NumberUtils.toFloat("1.5")  = 1.5f
+     * 
+ * + * @param str the string to convert, may be null + * @return the float represented by the string, or 0.0f + * if conversion fails + * @since 2.1 + */ + public static float toFloat(final String str) { + return toFloat(str, 0.0f); + } + + /** + *

Convert a String to a float, returning a + * default value if the conversion fails.

+ * + *

If the string str is null, the default + * value is returned.

+ * + *
+     *   NumberUtils.toFloat(null, 1.1f)   = 1.0f
+     *   NumberUtils.toFloat("", 1.1f)     = 1.1f
+     *   NumberUtils.toFloat("1.5", 0.0f)  = 1.5f
+     * 
+ * + * @param str the string to convert, may be null + * @param defaultValue the default value + * @return the float represented by the string, or defaultValue + * if conversion fails + * @since 2.1 + */ + public static float toFloat(final String str, final float defaultValue) { + if (str == null) { + return defaultValue; + } + try { + return Float.parseFloat(str); + } catch (final NumberFormatException nfe) { + return defaultValue; + } + } + + /** + *

Convert a String to a double, returning + * 0.0d if the conversion fails.

+ * + *

If the string str is null, + * 0.0d is returned.

+ * + *
+     *   NumberUtils.toDouble(null)   = 0.0d
+     *   NumberUtils.toDouble("")     = 0.0d
+     *   NumberUtils.toDouble("1.5")  = 1.5d
+     * 
+ * + * @param str the string to convert, may be null + * @return the double represented by the string, or 0.0d + * if conversion fails + * @since 2.1 + */ + public static double toDouble(final String str) { + return toDouble(str, 0.0d); + } + + /** + *

Convert a String to a double, returning a + * default value if the conversion fails.

+ * + *

If the string str is null, the default + * value is returned.

+ * + *
+     *   NumberUtils.toDouble(null, 1.1d)   = 1.1d
+     *   NumberUtils.toDouble("", 1.1d)     = 1.1d
+     *   NumberUtils.toDouble("1.5", 0.0d)  = 1.5d
+     * 
+ * + * @param str the string to convert, may be null + * @param defaultValue the default value + * @return the double represented by the string, or defaultValue + * if conversion fails + * @since 2.1 + */ + public static double toDouble(final String str, final double defaultValue) { + if (str == null) { + return defaultValue; + } + try { + return Double.parseDouble(str); + } catch (final NumberFormatException nfe) { + return defaultValue; + } + } + + //----------------------------------------------------------------------- + /** + *

Convert a String to a byte, returning + * zero if the conversion fails.

+ * + *

If the string is null, zero is returned.

+ * + *
+     *   NumberUtils.toByte(null) = 0
+     *   NumberUtils.toByte("")   = 0
+     *   NumberUtils.toByte("1")  = 1
+     * 
+ * + * @param str the string to convert, may be null + * @return the byte represented by the string, or zero if + * conversion fails + * @since 2.5 + */ + public static byte toByte(final String str) { + return toByte(str, (byte) 0); + } + + /** + *

Convert a String to a byte, returning a + * default value if the conversion fails.

+ * + *

If the string is null, the default value is returned.

+ * + *
+     *   NumberUtils.toByte(null, 1) = 1
+     *   NumberUtils.toByte("", 1)   = 1
+     *   NumberUtils.toByte("1", 0)  = 1
+     * 
+ * + * @param str the string to convert, may be null + * @param defaultValue the default value + * @return the byte represented by the string, or the default if conversion fails + * @since 2.5 + */ + public static byte toByte(final String str, final byte defaultValue) { + if(str == null) { + return defaultValue; + } + try { + return Byte.parseByte(str); + } catch (final NumberFormatException nfe) { + return defaultValue; + } + } + + /** + *

Convert a String to a short, returning + * zero if the conversion fails.

+ * + *

If the string is null, zero is returned.

+ * + *
+     *   NumberUtils.toShort(null) = 0
+     *   NumberUtils.toShort("")   = 0
+     *   NumberUtils.toShort("1")  = 1
+     * 
+ * + * @param str the string to convert, may be null + * @return the short represented by the string, or zero if + * conversion fails + * @since 2.5 + */ + public static short toShort(final String str) { + return toShort(str, (short) 0); + } + + /** + *

Convert a String to an short, returning a + * default value if the conversion fails.

+ * + *

If the string is null, the default value is returned.

+ * + *
+     *   NumberUtils.toShort(null, 1) = 1
+     *   NumberUtils.toShort("", 1)   = 1
+     *   NumberUtils.toShort("1", 0)  = 1
+     * 
+ * + * @param str the string to convert, may be null + * @param defaultValue the default value + * @return the short represented by the string, or the default if conversion fails + * @since 2.5 + */ + public static short toShort(final String str, final short defaultValue) { + if(str == null) { + return defaultValue; + } + try { + return Short.parseShort(str); + } catch (final NumberFormatException nfe) { + return defaultValue; + } + } + + //----------------------------------------------------------------------- + // must handle Long, Float, Integer, Float, Short, + // BigDecimal, BigInteger and Byte + // useful methods: + // Byte.decode(String) + // Byte.valueOf(String,int radix) + // Byte.valueOf(String) + // Double.valueOf(String) + // Float.valueOf(String) + // Float.valueOf(String) + // Integer.valueOf(String,int radix) + // Integer.valueOf(String) + // Integer.decode(String) + // Integer.getInteger(String) + // Integer.getInteger(String,int val) + // Integer.getInteger(String,Integer val) + // Integer.valueOf(String) + // Double.valueOf(String) + // new Byte(String) + // Long.valueOf(String) + // Long.getLong(String) + // Long.getLong(String,int) + // Long.getLong(String,Integer) + // Long.valueOf(String,int) + // Long.valueOf(String) + // Short.valueOf(String) + // Short.decode(String) + // Short.valueOf(String,int) + // Short.valueOf(String) + // new BigDecimal(String) + // new BigInteger(String) + // new BigInteger(String,int radix) + // Possible inputs: + // 45 45.5 45E7 4.5E7 Hex Oct Binary xxxF xxxD xxxf xxxd + // plus minus everything. Prolly more. A lot are not separable. + + /** + *

Turns a string value into a java.lang.Number.

+ * + *

If the string starts with {@code 0x} or {@code -0x} (lower or upper case) or {@code #} or {@code -#}, it + * will be interpreted as a hexadecimal Integer - or Long, if the number of digits after the + * prefix is more than 8 - or BigInteger if there are more than 16 digits. + *

+ *

Then, the value is examined for a type qualifier on the end, i.e. one of + * 'f','F','d','D','l','L'. If it is found, it starts + * trying to create successively larger types from the type specified + * until one is found that can represent the value.

+ * + *

If a type specifier is not found, it will check for a decimal point + * and then try successively larger types from Integer to + * BigInteger and from Float to + * BigDecimal.

+ * + *

+ * Integral values with a leading {@code 0} will be interpreted as octal; the returned number will + * be Integer, Long or BigDecimal as appropriate. + *

+ * + *

Returns null if the string is null.

+ * + *

This method does not trim the input string, i.e., strings with leading + * or trailing spaces will generate NumberFormatExceptions.

+ * + * @param str String containing a number, may be null + * @return Number created from the string (or null if the input is null) + * @throws NumberFormatException if the value cannot be converted + */ + public static Number createNumber(final String str) throws NumberFormatException { + if (str == null) { + return null; + } + if (StringUtils.isBlank(str)) { + throw new NumberFormatException("A blank string is not a valid number"); + } + // Need to deal with all possible hex prefixes here + final String[] hex_prefixes = {"0x", "0X", "-0x", "-0X", "#", "-#"}; + int pfxLen = 0; + for(final String pfx : hex_prefixes) { + if (str.startsWith(pfx)) { + pfxLen += pfx.length(); + break; + } + } + if (pfxLen > 0) { // we have a hex number + char firstSigDigit = 0; // strip leading zeroes + for(int i = pfxLen; i < str.length(); i++) { + firstSigDigit = str.charAt(i); + if (firstSigDigit == '0') { // count leading zeroes + pfxLen++; + } else { + break; + } + } + final int hexDigits = str.length() - pfxLen; + if (hexDigits > 16 || hexDigits == 16 && firstSigDigit > '7') { // too many for Long + return createBigInteger(str); + } + if (hexDigits > 8 || hexDigits == 8 && firstSigDigit > '7') { // too many for an int + return createLong(str); + } + return createInteger(str); + } + final char lastChar = str.charAt(str.length() - 1); + String mant; + String dec; + String exp; + final int decPos = str.indexOf('.'); + final int expPos = str.indexOf('e') + str.indexOf('E') + 1; // assumes both not present + // if both e and E are present, this is caught by the checks on expPos (which prevent IOOBE) + // and the parsing which will detect if e or E appear in a number due to using the wrong offset + + if (decPos > -1) { // there is a decimal point + if (expPos > -1) { // there is an exponent + if (expPos < decPos || expPos > str.length()) { // prevents double exponent causing IOOBE + throw new NumberFormatException(str + " is not a valid number."); + } + dec = str.substring(decPos + 1, expPos); + } else { + dec = str.substring(decPos + 1); + } + mant = getMantissa(str, decPos); + } else { + if (expPos > -1) { + if (expPos > str.length()) { // prevents double exponent causing IOOBE + throw new NumberFormatException(str + " is not a valid number."); + } + mant = getMantissa(str, expPos); + } else { + mant = getMantissa(str); + } + dec = null; + } + if (!Character.isDigit(lastChar) && lastChar != '.') { + if (expPos > -1 && expPos < str.length() - 1) { + exp = str.substring(expPos + 1, str.length() - 1); + } else { + exp = null; + } + //Requesting a specific type.. + final String numeric = str.substring(0, str.length() - 1); + final boolean allZeros = isAllZeros(mant) && isAllZeros(exp); + switch (lastChar) { + case 'l' : + case 'L' : + if (dec == null + && exp == null + && (numeric.charAt(0) == '-' && isDigits(numeric.substring(1)) || isDigits(numeric))) { + try { + return createLong(numeric); + } catch (final NumberFormatException nfe) { // NOPMD + // Too big for a long + } + return createBigInteger(numeric); + + } + throw new NumberFormatException(str + " is not a valid number."); + case 'f' : + case 'F' : + try { + final Float f = NumberUtils.createFloat(str); + if (!(f.isInfinite() || f.floatValue() == 0.0F && !allZeros)) { + //If it's too big for a float or the float value = 0 and the string + //has non-zeros in it, then float does not have the precision we want + return f; + } + + } catch (final NumberFormatException nfe) { // NOPMD + // ignore the bad number + } + //$FALL-THROUGH$ + case 'd' : + case 'D' : + try { + final Double d = NumberUtils.createDouble(str); + if (!(d.isInfinite() || d.floatValue() == 0.0D && !allZeros)) { + return d; + } + } catch (final NumberFormatException nfe) { // NOPMD + // ignore the bad number + } + try { + return createBigDecimal(numeric); + } catch (final NumberFormatException e) { // NOPMD + // ignore the bad number + } + //$FALL-THROUGH$ + default : + throw new NumberFormatException(str + " is not a valid number."); + + } + } + //User doesn't have a preference on the return type, so let's start + //small and go from there... + if (expPos > -1 && expPos < str.length() - 1) { + exp = str.substring(expPos + 1, str.length()); + } else { + exp = null; + } + if (dec == null && exp == null) { // no decimal point and no exponent + //Must be an Integer, Long, Biginteger + try { + return createInteger(str); + } catch (final NumberFormatException nfe) { // NOPMD + // ignore the bad number + } + try { + return createLong(str); + } catch (final NumberFormatException nfe) { // NOPMD + // ignore the bad number + } + return createBigInteger(str); + } + + //Must be a Float, Double, BigDecimal + final boolean allZeros = isAllZeros(mant) && isAllZeros(exp); + try { + final Float f = createFloat(str); + final Double d = createDouble(str); + if (!f.isInfinite() + && !(f.floatValue() == 0.0F && !allZeros) + && f.toString().equals(d.toString())) { + return f; + } + if (!d.isInfinite() && !(d.doubleValue() == 0.0D && !allZeros)) { + final BigDecimal b = createBigDecimal(str); + if (b.compareTo(BigDecimal.valueOf(d)) == 0) { + return d; + } + return b; + } + } catch (final NumberFormatException nfe) { // NOPMD + // ignore the bad number + } + return createBigDecimal(str); + } + + /** + *

Utility method for {@link #createNumber(java.lang.String)}.

+ * + *

Returns mantissa of the given number.

+ * + * @param str the string representation of the number + * @return mantissa of the given number + */ + private static String getMantissa(final String str) { + return getMantissa(str, str.length()); + } + + /** + *

Utility method for {@link #createNumber(java.lang.String)}.

+ * + *

Returns mantissa of the given number.

+ * + * @param str the string representation of the number + * @param stopPos the position of the exponent or decimal point + * @return mantissa of the given number + */ + private static String getMantissa(final String str, final int stopPos) { + final char firstChar = str.charAt(0); + final boolean hasSign = firstChar == '-' || firstChar == '+'; + + return hasSign ? str.substring(1, stopPos) : str.substring(0, stopPos); + } + + /** + *

Utility method for {@link #createNumber(java.lang.String)}.

+ * + *

Returns true if s is null.

+ * + * @param str the String to check + * @return if it is all zeros or null + */ + private static boolean isAllZeros(final String str) { + if (str == null) { + return true; + } + for (int i = str.length() - 1; i >= 0; i--) { + if (str.charAt(i) != '0') { + return false; + } + } + return str.length() > 0; + } + + //----------------------------------------------------------------------- + /** + *

Convert a String to a Float.

+ * + *

Returns null if the string is null.

+ * + * @param str a String to convert, may be null + * @return converted Float (or null if the input is null) + * @throws NumberFormatException if the value cannot be converted + */ + public static Float createFloat(final String str) { + if (str == null) { + return null; + } + return Float.valueOf(str); + } + + /** + *

Convert a String to a Double.

+ * + *

Returns null if the string is null.

+ * + * @param str a String to convert, may be null + * @return converted Double (or null if the input is null) + * @throws NumberFormatException if the value cannot be converted + */ +/** + *

Convert a String to a Double.

+ * + *

Returns null if the string is null.

+ * + * @param str + * a String to convert, may be null + * @return converted Double (or null if the input is null) + * @throws NumberFormatException + * if the value cannot be converted + */ +public static java.lang.Double createDouble(final java.lang.String str) { + { + return java.lang.Double.valueOf(/* NPEX_NULL_EXP */ + str); + } +} + + /** + *

Convert a String to a Integer, handling + * hex (0xhhhh) and octal (0dddd) notations. + * N.B. a leading zero means octal; spaces are not trimmed.

+ * + *

Returns null if the string is null.

+ * + * @param str a String to convert, may be null + * @return converted Integer (or null if the input is null) + * @throws NumberFormatException if the value cannot be converted + */ + public static Integer createInteger(final String str) { + if (str == null) { + return null; + } + // decode() handles 0xAABD and 0777 (hex and octal) as well. + return Integer.decode(str); + } + + /** + *

Convert a String to a Long; + * since 3.1 it handles hex (0Xhhhh) and octal (0ddd) notations. + * N.B. a leading zero means octal; spaces are not trimmed.

+ * + *

Returns null if the string is null.

+ * + * @param str a String to convert, may be null + * @return converted Long (or null if the input is null) + * @throws NumberFormatException if the value cannot be converted + */ + public static Long createLong(final String str) { + if (str == null) { + return null; + } + return Long.decode(str); + } + + /** + *

Convert a String to a BigInteger; + * since 3.2 it handles hex (0x or #) and octal (0) notations.

+ * + *

Returns null if the string is null.

+ * + * @param str a String to convert, may be null + * @return converted BigInteger (or null if the input is null) + * @throws NumberFormatException if the value cannot be converted + */ + public static BigInteger createBigInteger(final String str) { + if (str == null) { + return null; + } + int pos = 0; // offset within string + int radix = 10; + boolean negate = false; // need to negate later? + if (str.startsWith("-")) { + negate = true; + pos = 1; + } + if (str.startsWith("0x", pos) || str.startsWith("0X", pos)) { // hex + radix = 16; + pos += 2; + } else if (str.startsWith("#", pos)) { // alternative hex (allowed by Long/Integer) + radix = 16; + pos ++; + } else if (str.startsWith("0", pos) && str.length() > pos + 1) { // octal; so long as there are additional digits + radix = 8; + pos ++; + } // default is to treat as decimal + + final BigInteger value = new BigInteger(str.substring(pos), radix); + return negate ? value.negate() : value; + } + + /** + *

Convert a String to a BigDecimal.

+ * + *

Returns null if the string is null.

+ * + * @param str a String to convert, may be null + * @return converted BigDecimal (or null if the input is null) + * @throws NumberFormatException if the value cannot be converted + */ + public static BigDecimal createBigDecimal(final String str) { + if (str == null) { + return null; + } + // handle JDK1.3.1 bug where "" throws IndexOutOfBoundsException + if (StringUtils.isBlank(str)) { + throw new NumberFormatException("A blank string is not a valid number"); + } + if (str.trim().startsWith("--")) { + // this is protection for poorness in java.lang.BigDecimal. + // it accepts this as a legal value, but it does not appear + // to be in specification of class. OS X Java parses it to + // a wrong value. + throw new NumberFormatException(str + " is not a valid number."); + } + return new BigDecimal(str); + } + + // Min in array + //-------------------------------------------------------------------- + /** + *

Returns the minimum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the minimum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @since 3.4 Changed signature from min(long[]) to min(long...) + */ + public static long min(final long... array) { + // Validates input + validateArray(array); + + // Finds and returns min + long min = array[0]; + for (int i = 1; i < array.length; i++) { + if (array[i] < min) { + min = array[i]; + } + } + + return min; + } + + /** + *

Returns the minimum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the minimum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @since 3.4 Changed signature from min(int[]) to min(int...) + */ + public static int min(final int... array) { + // Validates input + validateArray(array); + + // Finds and returns min + int min = array[0]; + for (int j = 1; j < array.length; j++) { + if (array[j] < min) { + min = array[j]; + } + } + + return min; + } + + /** + *

Returns the minimum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the minimum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @since 3.4 Changed signature from min(short[]) to min(short...) + */ + public static short min(final short... array) { + // Validates input + validateArray(array); + + // Finds and returns min + short min = array[0]; + for (int i = 1; i < array.length; i++) { + if (array[i] < min) { + min = array[i]; + } + } + + return min; + } + + /** + *

Returns the minimum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the minimum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @since 3.4 Changed signature from min(byte[]) to min(byte...) + */ + public static byte min(final byte... array) { + // Validates input + validateArray(array); + + // Finds and returns min + byte min = array[0]; + for (int i = 1; i < array.length; i++) { + if (array[i] < min) { + min = array[i]; + } + } + + return min; + } + + /** + *

Returns the minimum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the minimum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @see IEEE754rUtils#min(double[]) IEEE754rUtils for a version of this method that handles NaN differently + * @since 3.4 Changed signature from min(double[]) to min(double...) + */ + public static double min(final double... array) { + // Validates input + validateArray(array); + + // Finds and returns min + double min = array[0]; + for (int i = 1; i < array.length; i++) { + if (Double.isNaN(array[i])) { + return Double.NaN; + } + if (array[i] < min) { + min = array[i]; + } + } + + return min; + } + + /** + *

Returns the minimum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the minimum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @see IEEE754rUtils#min(float[]) IEEE754rUtils for a version of this method that handles NaN differently + * @since 3.4 Changed signature from min(float[]) to min(float...) + */ + public static float min(final float... array) { + // Validates input + validateArray(array); + + // Finds and returns min + float min = array[0]; + for (int i = 1; i < array.length; i++) { + if (Float.isNaN(array[i])) { + return Float.NaN; + } + if (array[i] < min) { + min = array[i]; + } + } + + return min; + } + + // Max in array + //-------------------------------------------------------------------- + /** + *

Returns the maximum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the maximum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @since 3.4 Changed signature from max(long[]) to max(long...) + */ + public static long max(final long... array) { + // Validates input + validateArray(array); + + // Finds and returns max + long max = array[0]; + for (int j = 1; j < array.length; j++) { + if (array[j] > max) { + max = array[j]; + } + } + + return max; + } + + /** + *

Returns the maximum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the maximum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @since 3.4 Changed signature from max(int[]) to max(int...) + */ + public static int max(final int... array) { + // Validates input + validateArray(array); + + // Finds and returns max + int max = array[0]; + for (int j = 1; j < array.length; j++) { + if (array[j] > max) { + max = array[j]; + } + } + + return max; + } + + /** + *

Returns the maximum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the maximum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @since 3.4 Changed signature from max(short[]) to max(short...) + */ + public static short max(final short... array) { + // Validates input + validateArray(array); + + // Finds and returns max + short max = array[0]; + for (int i = 1; i < array.length; i++) { + if (array[i] > max) { + max = array[i]; + } + } + + return max; + } + + /** + *

Returns the maximum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the maximum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @since 3.4 Changed signature from max(byte[]) to max(byte...) + */ + public static byte max(final byte... array) { + // Validates input + validateArray(array); + + // Finds and returns max + byte max = array[0]; + for (int i = 1; i < array.length; i++) { + if (array[i] > max) { + max = array[i]; + } + } + + return max; + } + + /** + *

Returns the maximum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the maximum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @see IEEE754rUtils#max(double[]) IEEE754rUtils for a version of this method that handles NaN differently + * @since 3.4 Changed signature from max(double[]) to max(double...) + */ + public static double max(final double... array) { + // Validates input + validateArray(array); + + // Finds and returns max + double max = array[0]; + for (int j = 1; j < array.length; j++) { + if (Double.isNaN(array[j])) { + return Double.NaN; + } + if (array[j] > max) { + max = array[j]; + } + } + + return max; + } + + /** + *

Returns the maximum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the maximum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @see IEEE754rUtils#max(float[]) IEEE754rUtils for a version of this method that handles NaN differently + * @since 3.4 Changed signature from max(float[]) to max(float...) + */ + public static float max(final float... array) { + // Validates input + validateArray(array); + + // Finds and returns max + float max = array[0]; + for (int j = 1; j < array.length; j++) { + if (Float.isNaN(array[j])) { + return Float.NaN; + } + if (array[j] > max) { + max = array[j]; + } + } + + return max; + } + + /** + * Checks if the specified array is neither null nor empty. + * + * @param array the array to check + * @throws IllegalArgumentException if {@code array} is either {@code null} or empty + */ + private static void validateArray(final Object array) { + if (array == null) { + throw new IllegalArgumentException("The Array must not be null"); + } + Validate.isTrue(Array.getLength(array) != 0, "Array cannot be empty."); + } + + // 3 param min + //----------------------------------------------------------------------- + /** + *

Gets the minimum of three long values.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the smallest of the values + */ + public static long min(long a, final long b, final long c) { + if (b < a) { + a = b; + } + if (c < a) { + a = c; + } + return a; + } + + /** + *

Gets the minimum of three int values.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the smallest of the values + */ + public static int min(int a, final int b, final int c) { + if (b < a) { + a = b; + } + if (c < a) { + a = c; + } + return a; + } + + /** + *

Gets the minimum of three short values.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the smallest of the values + */ + public static short min(short a, final short b, final short c) { + if (b < a) { + a = b; + } + if (c < a) { + a = c; + } + return a; + } + + /** + *

Gets the minimum of three byte values.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the smallest of the values + */ + public static byte min(byte a, final byte b, final byte c) { + if (b < a) { + a = b; + } + if (c < a) { + a = c; + } + return a; + } + + /** + *

Gets the minimum of three double values.

+ * + *

If any value is NaN, NaN is + * returned. Infinity is handled.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the smallest of the values + * @see IEEE754rUtils#min(double, double, double) for a version of this method that handles NaN differently + */ + public static double min(final double a, final double b, final double c) { + return Math.min(Math.min(a, b), c); + } + + /** + *

Gets the minimum of three float values.

+ * + *

If any value is NaN, NaN is + * returned. Infinity is handled.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the smallest of the values + * @see IEEE754rUtils#min(float, float, float) for a version of this method that handles NaN differently + */ + public static float min(final float a, final float b, final float c) { + return Math.min(Math.min(a, b), c); + } + + // 3 param max + //----------------------------------------------------------------------- + /** + *

Gets the maximum of three long values.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the largest of the values + */ + public static long max(long a, final long b, final long c) { + if (b > a) { + a = b; + } + if (c > a) { + a = c; + } + return a; + } + + /** + *

Gets the maximum of three int values.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the largest of the values + */ + public static int max(int a, final int b, final int c) { + if (b > a) { + a = b; + } + if (c > a) { + a = c; + } + return a; + } + + /** + *

Gets the maximum of three short values.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the largest of the values + */ + public static short max(short a, final short b, final short c) { + if (b > a) { + a = b; + } + if (c > a) { + a = c; + } + return a; + } + + /** + *

Gets the maximum of three byte values.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the largest of the values + */ + public static byte max(byte a, final byte b, final byte c) { + if (b > a) { + a = b; + } + if (c > a) { + a = c; + } + return a; + } + + /** + *

Gets the maximum of three double values.

+ * + *

If any value is NaN, NaN is + * returned. Infinity is handled.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the largest of the values + * @see IEEE754rUtils#max(double, double, double) for a version of this method that handles NaN differently + */ + public static double max(final double a, final double b, final double c) { + return Math.max(Math.max(a, b), c); + } + + /** + *

Gets the maximum of three float values.

+ * + *

If any value is NaN, NaN is + * returned. Infinity is handled.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the largest of the values + * @see IEEE754rUtils#max(float, float, float) for a version of this method that handles NaN differently + */ + public static float max(final float a, final float b, final float c) { + return Math.max(Math.max(a, b), c); + } + + //----------------------------------------------------------------------- + /** + *

Checks whether the String contains only + * digit characters.

+ * + *

Null and empty String will return + * false.

+ * + * @param str the String to check + * @return true if str contains only Unicode numeric + */ + public static boolean isDigits(final String str) { + return StringUtils.isNumeric(str); + } + + /** + *

Checks whether the String a valid Java number.

+ * + *

Valid numbers include hexadecimal marked with the 0x or + * 0X qualifier, octal numbers, scientific notation and + * numbers marked with a type qualifier (e.g. 123L).

+ * + *

Non-hexadecimal strings beginning with a leading zero are + * treated as octal values. Thus the string 09 will return + * false, since 9 is not a valid octal value. + * However, numbers beginning with {@code 0.} are treated as decimal.

+ * + *

null and empty/blank {@code String} will return + * false.

+ * + *

Note, {@link #createNumber(String)} should return a number for every + * input resuling in true.

+ * + * @param str the String to check + * @return true if the string is a correctly formatted number + * @since 3.3 the code supports hex {@code 0Xhhh} an + * octal {@code 0ddd} validation + * @deprecated This feature will be removed in Lang 4.0, + * use {@link NumberUtils#isCreatable(String)} instead + */ + @Deprecated + public static boolean isNumber(final String str) { + return isCreatable(str); + } + + /** + *

Checks whether the String a valid Java number.

+ * + *

Valid numbers include hexadecimal marked with the 0x or + * 0X qualifier, octal numbers, scientific notation and + * numbers marked with a type qualifier (e.g. 123L).

+ * + *

Non-hexadecimal strings beginning with a leading zero are + * treated as octal values. Thus the string 09 will return + * false, since 9 is not a valid octal value. + * However, numbers beginning with {@code 0.} are treated as decimal.

+ * + *

null and empty/blank {@code String} will return + * false.

+ * + *

Note, {@link #createNumber(String)} should return a number for every + * input resuling in true.

+ * + * @param str the String to check + * @return true if the string is a correctly formatted number + * @since 3.5 the code supports the "+" suffix on numbers except for integers in Java 1.6 + */ + public static boolean isCreatable(final String str) { + if (StringUtils.isEmpty(str)) { + return false; + } + final char[] chars = str.toCharArray(); + int sz = chars.length; + boolean hasExp = false; + boolean hasDecPoint = false; + boolean allowSigns = false; + boolean foundDigit = false; + // deal with any possible sign up front + final int start = chars[0] == '-' || chars[0] == '+' ? 1 : 0; + final boolean hasLeadingPlusSign = start == 1 && chars[0] == '+'; + if (sz > start + 1 && chars[start] == '0') { // leading 0 + if (chars[start + 1] == 'x' || chars[start + 1] == 'X') { // leading 0x/0X + int i = start + 2; + if (i == sz) { + return false; // str == "0x" + } + // checking hex (it can't be anything else) + for (; i < chars.length; i++) { + if ((chars[i] < '0' || chars[i] > '9') + && (chars[i] < 'a' || chars[i] > 'f') + && (chars[i] < 'A' || chars[i] > 'F')) { + return false; + } + } + return true; + } else if (Character.isDigit(chars[start + 1])) { + // leading 0, but not hex, must be octal + int i = start + 1; + for (; i < chars.length; i++) { + if (chars[i] < '0' || chars[i] > '7') { + return false; + } + } + return true; + } + } + sz--; // don't want to loop to the last char, check it afterwords + // for type qualifiers + int i = start; + // loop to the next to last char or to the last char if we need another digit to + // make a valid number (e.g. chars[0..5] = "1234E") + while (i < sz || i < sz + 1 && allowSigns && !foundDigit) { + if (chars[i] >= '0' && chars[i] <= '9') { + foundDigit = true; + allowSigns = false; + + } else if (chars[i] == '.') { + if (hasDecPoint || hasExp) { + // two decimal points or dec in exponent + return false; + } + hasDecPoint = true; + } else if (chars[i] == 'e' || chars[i] == 'E') { + // we've already taken care of hex. + if (hasExp) { + // two E's + return false; + } + if (!foundDigit) { + return false; + } + hasExp = true; + allowSigns = true; + } else if (chars[i] == '+' || chars[i] == '-') { + if (!allowSigns) { + return false; + } + allowSigns = false; + foundDigit = false; // we need a digit after the E + } else { + return false; + } + i++; + } + if (i < chars.length) { + if (chars[i] >= '0' && chars[i] <= '9') { + if (SystemUtils.IS_JAVA_1_6 && hasLeadingPlusSign && !hasDecPoint) { + return false; + } + // no type qualifier, OK + return true; + } + if (chars[i] == 'e' || chars[i] == 'E') { + // can't have an E at the last byte + return false; + } + if (chars[i] == '.') { + if (hasDecPoint || hasExp) { + // two decimal points or dec in exponent + return false; + } + // single trailing decimal point after non-exponent is ok + return foundDigit; + } + if (!allowSigns + && (chars[i] == 'd' + || chars[i] == 'D' + || chars[i] == 'f' + || chars[i] == 'F')) { + return foundDigit; + } + if (chars[i] == 'l' + || chars[i] == 'L') { + // not allowing L with an exponent or decimal point + return foundDigit && !hasExp && !hasDecPoint; + } + // last character is illegal + return false; + } + // allowSigns is true iff the val ends in 'E' + // found digit it to make sure weird stuff like '.' and '1E-' doesn't pass + return !allowSigns && foundDigit; + } + + /** + *

Checks whether the given String is a parsable number.

+ * + *

Parsable numbers include those Strings understood by {@link Integer#parseInt(String)}, + * {@link Long#parseLong(String)}, {@link Float#parseFloat(String)} or + * {@link Double#parseDouble(String)}. This method can be used instead of catching {@link java.text.ParseException} + * when calling one of those methods.

+ * + *

Hexadecimal and scientific notations are not considered parsable. + * See {@link #isCreatable(String)} on those cases.

+ * + *

{@code Null} and empty String will return false.

+ * + * @param str the String to check. + * @return {@code true} if the string is a parsable number. + * @since 3.4 + */ + public static boolean isParsable(final String str) { + if (StringUtils.isEmpty(str)) { + return false; + } + if (str.charAt(str.length() - 1) == '.') { + return false; + } + if (str.charAt(0) == '-') { + if (str.length() == 1) { + return false; + } + return withDecimalsParsing(str, 1); + } else { + return withDecimalsParsing(str, 0); + } + } + + private static boolean withDecimalsParsing(final String str, final int beginIdx) { + int decimalPoints = 0; + for (int i = beginIdx; i < str.length(); i++) { + final boolean isDecimalPoint = str.charAt(i) == '.'; + if (isDecimalPoint) { + decimalPoints++; + } + if (decimalPoints > 1) { + return false; + } + if (!isDecimalPoint && !Character.isDigit(str.charAt(i))) { + return false; + } + } + return true; + } + + /** + *

Compares two {@code int} values numerically. This is the same functionality as provided in Java 7.

+ * + * @param x the first {@code int} to compare + * @param y the second {@code int} 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(int x, int y) { + if (x == y) { + return 0; + } + return x < y ? -1 : 1; + } + + /** + *

Compares to {@code long} values numerically. This is the same functionality as provided in Java 7.

+ * + * @param x the first {@code long} to compare + * @param y the second {@code long} 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(long x, long y) { + if (x == y) { + return 0; + } + return x < y ? -1 : 1; + } + + /** + *

Compares to {@code short} values numerically. This is the same functionality as provided in Java 7.

+ * + * @param x the first {@code short} to compare + * @param y the second {@code short} 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(short x, short y) { + if (x == y) { + return 0; + } + return x < y ? -1 : 1; + } + + /** + *

Compares two {@code byte} values numerically. This is the same functionality as provided in Java 7.

+ * + * @param x the first {@code byte} to compare + * @param y the second {@code byte} 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(byte x, byte y) { + return x - y; + } +} diff --git a/Java/commons-lang-NumberUtils_695/metadata.json b/Java/commons-lang-NumberUtils_695/metadata.json new file mode 100644 index 000000000..41b2bb026 --- /dev/null +++ b/Java/commons-lang-NumberUtils_695/metadata.json @@ -0,0 +1,21 @@ +{ + "language": "java", + "id": "commons-lang-NumberUtils_695", + "buggyPath": ".", + "referencePath": null, + "buildCommand": "mvn package -V -B -Denforcer.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true -Drat.skip=true -Dlicense.skip=true -Dfindbugs.skip=true -Dgpg.skip=true -Dskip.npm=true -Dskip.gulp=true -Dskip.bower=true -Drat.numUnapprovedLicenses=100 -DskipTests=true -DskipITs=true -Dtest=None -DfailIfNoTests=false", + "testCommand": "mvn test -V -B -Denforcer.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true -Drat.skip=true -Dlicense.skip=true -Dfindbugs.skip=true -Dgpg.skip=true -Dskip.npm=true -Dskip.gulp=true -Dskip.bower=true -Drat.numUnapprovedLicenses=100", + "categories": [ + "safety", + "npe" + ], + "npe": { + "filepath": "src/main/java/org/apache/commons/lang3/math/NumberUtils.java", + "line": 708, + "npe_method": "createDouble", + "deref_field": "str", + "npe_class": "NumberUtils", + "repo": "commons-lang", + "bug_id": "NumberUtils_695" + } +} diff --git a/Java/commons-lang-NumberUtils_695/npe.json b/Java/commons-lang-NumberUtils_695/npe.json new file mode 100644 index 000000000..b2f2df8fc --- /dev/null +++ b/Java/commons-lang-NumberUtils_695/npe.json @@ -0,0 +1,7 @@ +{ + "filepath": "src/main/java/org/apache/commons/lang3/math/NumberUtils.java", + "line": 708, + "npe_method": "createDouble", + "deref_field": "str", + "npe_class": "NumberUtils" +} \ No newline at end of file diff --git a/Java/commons-lang-NumberUtils_713/Dockerfile b/Java/commons-lang-NumberUtils_713/Dockerfile new file mode 100644 index 000000000..7b7fbe349 --- /dev/null +++ b/Java/commons-lang-NumberUtils_713/Dockerfile @@ -0,0 +1,18 @@ +FROM ghcr.io/kupl/starlab-benchmarks/java-base:commons-lang + +ENV TZ=Asia/Seoul + +COPY ./metadata.json . +COPY ./npe.json . +COPY ./buggy.java /tmp/buggy.java +RUN export BUGGY_PATH=$(cat metadata.json | jq -r ".npe.filepath") \ + && export BUGGY_LINE=$(cat metadata.json | jq -r ".npe.line") \ + && export BUGGY_MTHD=$(cat metadata.json | jq -r ".npe.npe_method") \ + && mv /tmp/buggy.java $BUGGY_PATH \ + && echo "[{\"filepath\": \"$BUGGY_PATH\", \"line\": $BUGGY_LINE, \"method_name\": \"$BUGGY_MTHD\"}]" | jq . > traces.json + +RUN git init . && git add -A + +RUN $(cat metadata.json | jq -r ".buildCommand") + +RUN $(cat metadata.json | jq -r ".testCommand"); if [ $? -eq 0 ]; then exit 1; fi diff --git a/Java/commons-lang-NumberUtils_713/buggy.java b/Java/commons-lang-NumberUtils_713/buggy.java new file mode 100644 index 000000000..b9890f09a --- /dev/null +++ b/Java/commons-lang-NumberUtils_713/buggy.java @@ -0,0 +1,1646 @@ +/* + * 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 java.lang.reflect.Array; +import java.math.BigDecimal; +import java.math.BigInteger; + +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.SystemUtils; +import org.apache.commons.lang3.Validate; + +/** + *

Provides extra functionality for Java Number classes.

+ * + * @since 2.0 + */ +public class NumberUtils { + + /** Reusable Long constant for zero. */ + public static final Long LONG_ZERO = Long.valueOf(0L); + /** Reusable Long constant for one. */ + public static final Long LONG_ONE = Long.valueOf(1L); + /** Reusable Long constant for minus one. */ + public static final Long LONG_MINUS_ONE = Long.valueOf(-1L); + /** Reusable Integer constant for zero. */ + public static final Integer INTEGER_ZERO = Integer.valueOf(0); + /** Reusable Integer constant for one. */ + public static final Integer INTEGER_ONE = Integer.valueOf(1); + /** Reusable Integer constant for minus one. */ + public static final Integer INTEGER_MINUS_ONE = Integer.valueOf(-1); + /** Reusable Short constant for zero. */ + public static final Short SHORT_ZERO = Short.valueOf((short) 0); + /** Reusable Short constant for one. */ + public static final Short SHORT_ONE = Short.valueOf((short) 1); + /** Reusable Short constant for minus one. */ + public static final Short SHORT_MINUS_ONE = Short.valueOf((short) -1); + /** Reusable Byte constant for zero. */ + public static final Byte BYTE_ZERO = Byte.valueOf((byte) 0); + /** Reusable Byte constant for one. */ + public static final Byte BYTE_ONE = Byte.valueOf((byte) 1); + /** Reusable Byte constant for minus one. */ + public static final Byte BYTE_MINUS_ONE = Byte.valueOf((byte) -1); + /** Reusable Double constant for zero. */ + public static final Double DOUBLE_ZERO = Double.valueOf(0.0d); + /** Reusable Double constant for one. */ + public static final Double DOUBLE_ONE = Double.valueOf(1.0d); + /** Reusable Double constant for minus one. */ + public static final Double DOUBLE_MINUS_ONE = Double.valueOf(-1.0d); + /** Reusable Float constant for zero. */ + public static final Float FLOAT_ZERO = Float.valueOf(0.0f); + /** Reusable Float constant for one. */ + public static final Float FLOAT_ONE = Float.valueOf(1.0f); + /** Reusable Float constant for minus one. */ + public static final Float FLOAT_MINUS_ONE = Float.valueOf(-1.0f); + + /** + *

NumberUtils instances should NOT be constructed in standard programming. + * Instead, the class should be used as NumberUtils.toInt("6");.

+ * + *

This constructor is public to permit tools that require a JavaBean instance + * to operate.

+ */ + public NumberUtils() { + super(); + } + + //----------------------------------------------------------------------- + /** + *

Convert a String to an int, returning + * zero if the conversion fails.

+ * + *

If the string is null, zero is returned.

+ * + *
+     *   NumberUtils.toInt(null) = 0
+     *   NumberUtils.toInt("")   = 0
+     *   NumberUtils.toInt("1")  = 1
+     * 
+ * + * @param str the string to convert, may be null + * @return the int represented by the string, or zero if + * conversion fails + * @since 2.1 + */ + public static int toInt(final String str) { + return toInt(str, 0); + } + + /** + *

Convert a String to an int, returning a + * default value if the conversion fails.

+ * + *

If the string is null, the default value is returned.

+ * + *
+     *   NumberUtils.toInt(null, 1) = 1
+     *   NumberUtils.toInt("", 1)   = 1
+     *   NumberUtils.toInt("1", 0)  = 1
+     * 
+ * + * @param str the string to convert, may be null + * @param defaultValue the default value + * @return the int represented by the string, or the default if conversion fails + * @since 2.1 + */ + public static int toInt(final String str, final int defaultValue) { + if(str == null) { + return defaultValue; + } + try { + return Integer.parseInt(str); + } catch (final NumberFormatException nfe) { + return defaultValue; + } + } + + /** + *

Convert a String to a long, returning + * zero if the conversion fails.

+ * + *

If the string is null, zero is returned.

+ * + *
+     *   NumberUtils.toLong(null) = 0L
+     *   NumberUtils.toLong("")   = 0L
+     *   NumberUtils.toLong("1")  = 1L
+     * 
+ * + * @param str the string to convert, may be null + * @return the long represented by the string, or 0 if + * conversion fails + * @since 2.1 + */ + public static long toLong(final String str) { + return toLong(str, 0L); + } + + /** + *

Convert a String to a long, returning a + * default value if the conversion fails.

+ * + *

If the string is null, the default value is returned.

+ * + *
+     *   NumberUtils.toLong(null, 1L) = 1L
+     *   NumberUtils.toLong("", 1L)   = 1L
+     *   NumberUtils.toLong("1", 0L)  = 1L
+     * 
+ * + * @param str the string to convert, may be null + * @param defaultValue the default value + * @return the long represented by the string, or the default if conversion fails + * @since 2.1 + */ + public static long toLong(final String str, final long defaultValue) { + if (str == null) { + return defaultValue; + } + try { + return Long.parseLong(str); + } catch (final NumberFormatException nfe) { + return defaultValue; + } + } + + /** + *

Convert a String to a float, returning + * 0.0f if the conversion fails.

+ * + *

If the string str is null, + * 0.0f is returned.

+ * + *
+     *   NumberUtils.toFloat(null)   = 0.0f
+     *   NumberUtils.toFloat("")     = 0.0f
+     *   NumberUtils.toFloat("1.5")  = 1.5f
+     * 
+ * + * @param str the string to convert, may be null + * @return the float represented by the string, or 0.0f + * if conversion fails + * @since 2.1 + */ + public static float toFloat(final String str) { + return toFloat(str, 0.0f); + } + + /** + *

Convert a String to a float, returning a + * default value if the conversion fails.

+ * + *

If the string str is null, the default + * value is returned.

+ * + *
+     *   NumberUtils.toFloat(null, 1.1f)   = 1.0f
+     *   NumberUtils.toFloat("", 1.1f)     = 1.1f
+     *   NumberUtils.toFloat("1.5", 0.0f)  = 1.5f
+     * 
+ * + * @param str the string to convert, may be null + * @param defaultValue the default value + * @return the float represented by the string, or defaultValue + * if conversion fails + * @since 2.1 + */ + public static float toFloat(final String str, final float defaultValue) { + if (str == null) { + return defaultValue; + } + try { + return Float.parseFloat(str); + } catch (final NumberFormatException nfe) { + return defaultValue; + } + } + + /** + *

Convert a String to a double, returning + * 0.0d if the conversion fails.

+ * + *

If the string str is null, + * 0.0d is returned.

+ * + *
+     *   NumberUtils.toDouble(null)   = 0.0d
+     *   NumberUtils.toDouble("")     = 0.0d
+     *   NumberUtils.toDouble("1.5")  = 1.5d
+     * 
+ * + * @param str the string to convert, may be null + * @return the double represented by the string, or 0.0d + * if conversion fails + * @since 2.1 + */ + public static double toDouble(final String str) { + return toDouble(str, 0.0d); + } + + /** + *

Convert a String to a double, returning a + * default value if the conversion fails.

+ * + *

If the string str is null, the default + * value is returned.

+ * + *
+     *   NumberUtils.toDouble(null, 1.1d)   = 1.1d
+     *   NumberUtils.toDouble("", 1.1d)     = 1.1d
+     *   NumberUtils.toDouble("1.5", 0.0d)  = 1.5d
+     * 
+ * + * @param str the string to convert, may be null + * @param defaultValue the default value + * @return the double represented by the string, or defaultValue + * if conversion fails + * @since 2.1 + */ + public static double toDouble(final String str, final double defaultValue) { + if (str == null) { + return defaultValue; + } + try { + return Double.parseDouble(str); + } catch (final NumberFormatException nfe) { + return defaultValue; + } + } + + //----------------------------------------------------------------------- + /** + *

Convert a String to a byte, returning + * zero if the conversion fails.

+ * + *

If the string is null, zero is returned.

+ * + *
+     *   NumberUtils.toByte(null) = 0
+     *   NumberUtils.toByte("")   = 0
+     *   NumberUtils.toByte("1")  = 1
+     * 
+ * + * @param str the string to convert, may be null + * @return the byte represented by the string, or zero if + * conversion fails + * @since 2.5 + */ + public static byte toByte(final String str) { + return toByte(str, (byte) 0); + } + + /** + *

Convert a String to a byte, returning a + * default value if the conversion fails.

+ * + *

If the string is null, the default value is returned.

+ * + *
+     *   NumberUtils.toByte(null, 1) = 1
+     *   NumberUtils.toByte("", 1)   = 1
+     *   NumberUtils.toByte("1", 0)  = 1
+     * 
+ * + * @param str the string to convert, may be null + * @param defaultValue the default value + * @return the byte represented by the string, or the default if conversion fails + * @since 2.5 + */ + public static byte toByte(final String str, final byte defaultValue) { + if(str == null) { + return defaultValue; + } + try { + return Byte.parseByte(str); + } catch (final NumberFormatException nfe) { + return defaultValue; + } + } + + /** + *

Convert a String to a short, returning + * zero if the conversion fails.

+ * + *

If the string is null, zero is returned.

+ * + *
+     *   NumberUtils.toShort(null) = 0
+     *   NumberUtils.toShort("")   = 0
+     *   NumberUtils.toShort("1")  = 1
+     * 
+ * + * @param str the string to convert, may be null + * @return the short represented by the string, or zero if + * conversion fails + * @since 2.5 + */ + public static short toShort(final String str) { + return toShort(str, (short) 0); + } + + /** + *

Convert a String to an short, returning a + * default value if the conversion fails.

+ * + *

If the string is null, the default value is returned.

+ * + *
+     *   NumberUtils.toShort(null, 1) = 1
+     *   NumberUtils.toShort("", 1)   = 1
+     *   NumberUtils.toShort("1", 0)  = 1
+     * 
+ * + * @param str the string to convert, may be null + * @param defaultValue the default value + * @return the short represented by the string, or the default if conversion fails + * @since 2.5 + */ + public static short toShort(final String str, final short defaultValue) { + if(str == null) { + return defaultValue; + } + try { + return Short.parseShort(str); + } catch (final NumberFormatException nfe) { + return defaultValue; + } + } + + //----------------------------------------------------------------------- + // must handle Long, Float, Integer, Float, Short, + // BigDecimal, BigInteger and Byte + // useful methods: + // Byte.decode(String) + // Byte.valueOf(String,int radix) + // Byte.valueOf(String) + // Double.valueOf(String) + // Float.valueOf(String) + // Float.valueOf(String) + // Integer.valueOf(String,int radix) + // Integer.valueOf(String) + // Integer.decode(String) + // Integer.getInteger(String) + // Integer.getInteger(String,int val) + // Integer.getInteger(String,Integer val) + // Integer.valueOf(String) + // Double.valueOf(String) + // new Byte(String) + // Long.valueOf(String) + // Long.getLong(String) + // Long.getLong(String,int) + // Long.getLong(String,Integer) + // Long.valueOf(String,int) + // Long.valueOf(String) + // Short.valueOf(String) + // Short.decode(String) + // Short.valueOf(String,int) + // Short.valueOf(String) + // new BigDecimal(String) + // new BigInteger(String) + // new BigInteger(String,int radix) + // Possible inputs: + // 45 45.5 45E7 4.5E7 Hex Oct Binary xxxF xxxD xxxf xxxd + // plus minus everything. Prolly more. A lot are not separable. + + /** + *

Turns a string value into a java.lang.Number.

+ * + *

If the string starts with {@code 0x} or {@code -0x} (lower or upper case) or {@code #} or {@code -#}, it + * will be interpreted as a hexadecimal Integer - or Long, if the number of digits after the + * prefix is more than 8 - or BigInteger if there are more than 16 digits. + *

+ *

Then, the value is examined for a type qualifier on the end, i.e. one of + * 'f','F','d','D','l','L'. If it is found, it starts + * trying to create successively larger types from the type specified + * until one is found that can represent the value.

+ * + *

If a type specifier is not found, it will check for a decimal point + * and then try successively larger types from Integer to + * BigInteger and from Float to + * BigDecimal.

+ * + *

+ * Integral values with a leading {@code 0} will be interpreted as octal; the returned number will + * be Integer, Long or BigDecimal as appropriate. + *

+ * + *

Returns null if the string is null.

+ * + *

This method does not trim the input string, i.e., strings with leading + * or trailing spaces will generate NumberFormatExceptions.

+ * + * @param str String containing a number, may be null + * @return Number created from the string (or null if the input is null) + * @throws NumberFormatException if the value cannot be converted + */ + public static Number createNumber(final String str) throws NumberFormatException { + if (str == null) { + return null; + } + if (StringUtils.isBlank(str)) { + throw new NumberFormatException("A blank string is not a valid number"); + } + // Need to deal with all possible hex prefixes here + final String[] hex_prefixes = {"0x", "0X", "-0x", "-0X", "#", "-#"}; + int pfxLen = 0; + for(final String pfx : hex_prefixes) { + if (str.startsWith(pfx)) { + pfxLen += pfx.length(); + break; + } + } + if (pfxLen > 0) { // we have a hex number + char firstSigDigit = 0; // strip leading zeroes + for(int i = pfxLen; i < str.length(); i++) { + firstSigDigit = str.charAt(i); + if (firstSigDigit == '0') { // count leading zeroes + pfxLen++; + } else { + break; + } + } + final int hexDigits = str.length() - pfxLen; + if (hexDigits > 16 || hexDigits == 16 && firstSigDigit > '7') { // too many for Long + return createBigInteger(str); + } + if (hexDigits > 8 || hexDigits == 8 && firstSigDigit > '7') { // too many for an int + return createLong(str); + } + return createInteger(str); + } + final char lastChar = str.charAt(str.length() - 1); + String mant; + String dec; + String exp; + final int decPos = str.indexOf('.'); + final int expPos = str.indexOf('e') + str.indexOf('E') + 1; // assumes both not present + // if both e and E are present, this is caught by the checks on expPos (which prevent IOOBE) + // and the parsing which will detect if e or E appear in a number due to using the wrong offset + + if (decPos > -1) { // there is a decimal point + if (expPos > -1) { // there is an exponent + if (expPos < decPos || expPos > str.length()) { // prevents double exponent causing IOOBE + throw new NumberFormatException(str + " is not a valid number."); + } + dec = str.substring(decPos + 1, expPos); + } else { + dec = str.substring(decPos + 1); + } + mant = getMantissa(str, decPos); + } else { + if (expPos > -1) { + if (expPos > str.length()) { // prevents double exponent causing IOOBE + throw new NumberFormatException(str + " is not a valid number."); + } + mant = getMantissa(str, expPos); + } else { + mant = getMantissa(str); + } + dec = null; + } + if (!Character.isDigit(lastChar) && lastChar != '.') { + if (expPos > -1 && expPos < str.length() - 1) { + exp = str.substring(expPos + 1, str.length() - 1); + } else { + exp = null; + } + //Requesting a specific type.. + final String numeric = str.substring(0, str.length() - 1); + final boolean allZeros = isAllZeros(mant) && isAllZeros(exp); + switch (lastChar) { + case 'l' : + case 'L' : + if (dec == null + && exp == null + && (numeric.charAt(0) == '-' && isDigits(numeric.substring(1)) || isDigits(numeric))) { + try { + return createLong(numeric); + } catch (final NumberFormatException nfe) { // NOPMD + // Too big for a long + } + return createBigInteger(numeric); + + } + throw new NumberFormatException(str + " is not a valid number."); + case 'f' : + case 'F' : + try { + final Float f = NumberUtils.createFloat(str); + if (!(f.isInfinite() || f.floatValue() == 0.0F && !allZeros)) { + //If it's too big for a float or the float value = 0 and the string + //has non-zeros in it, then float does not have the precision we want + return f; + } + + } catch (final NumberFormatException nfe) { // NOPMD + // ignore the bad number + } + //$FALL-THROUGH$ + case 'd' : + case 'D' : + try { + final Double d = NumberUtils.createDouble(str); + if (!(d.isInfinite() || d.floatValue() == 0.0D && !allZeros)) { + return d; + } + } catch (final NumberFormatException nfe) { // NOPMD + // ignore the bad number + } + try { + return createBigDecimal(numeric); + } catch (final NumberFormatException e) { // NOPMD + // ignore the bad number + } + //$FALL-THROUGH$ + default : + throw new NumberFormatException(str + " is not a valid number."); + + } + } + //User doesn't have a preference on the return type, so let's start + //small and go from there... + if (expPos > -1 && expPos < str.length() - 1) { + exp = str.substring(expPos + 1, str.length()); + } else { + exp = null; + } + if (dec == null && exp == null) { // no decimal point and no exponent + //Must be an Integer, Long, Biginteger + try { + return createInteger(str); + } catch (final NumberFormatException nfe) { // NOPMD + // ignore the bad number + } + try { + return createLong(str); + } catch (final NumberFormatException nfe) { // NOPMD + // ignore the bad number + } + return createBigInteger(str); + } + + //Must be a Float, Double, BigDecimal + final boolean allZeros = isAllZeros(mant) && isAllZeros(exp); + try { + final Float f = createFloat(str); + final Double d = createDouble(str); + if (!f.isInfinite() + && !(f.floatValue() == 0.0F && !allZeros) + && f.toString().equals(d.toString())) { + return f; + } + if (!d.isInfinite() && !(d.doubleValue() == 0.0D && !allZeros)) { + final BigDecimal b = createBigDecimal(str); + if (b.compareTo(BigDecimal.valueOf(d)) == 0) { + return d; + } + return b; + } + } catch (final NumberFormatException nfe) { // NOPMD + // ignore the bad number + } + return createBigDecimal(str); + } + + /** + *

Utility method for {@link #createNumber(java.lang.String)}.

+ * + *

Returns mantissa of the given number.

+ * + * @param str the string representation of the number + * @return mantissa of the given number + */ + private static String getMantissa(final String str) { + return getMantissa(str, str.length()); + } + + /** + *

Utility method for {@link #createNumber(java.lang.String)}.

+ * + *

Returns mantissa of the given number.

+ * + * @param str the string representation of the number + * @param stopPos the position of the exponent or decimal point + * @return mantissa of the given number + */ + private static String getMantissa(final String str, final int stopPos) { + final char firstChar = str.charAt(0); + final boolean hasSign = firstChar == '-' || firstChar == '+'; + + return hasSign ? str.substring(1, stopPos) : str.substring(0, stopPos); + } + + /** + *

Utility method for {@link #createNumber(java.lang.String)}.

+ * + *

Returns true if s is null.

+ * + * @param str the String to check + * @return if it is all zeros or null + */ + private static boolean isAllZeros(final String str) { + if (str == null) { + return true; + } + for (int i = str.length() - 1; i >= 0; i--) { + if (str.charAt(i) != '0') { + return false; + } + } + return str.length() > 0; + } + + //----------------------------------------------------------------------- + /** + *

Convert a String to a Float.

+ * + *

Returns null if the string is null.

+ * + * @param str a String to convert, may be null + * @return converted Float (or null if the input is null) + * @throws NumberFormatException if the value cannot be converted + */ + public static Float createFloat(final String str) { + if (str == null) { + return null; + } + return Float.valueOf(str); + } + + /** + *

Convert a String to a Double.

+ * + *

Returns null if the string is null.

+ * + * @param str a String to convert, may be null + * @return converted Double (or null if the input is null) + * @throws NumberFormatException if the value cannot be converted + */ + public static Double createDouble(final String str) { + if (str == null) { + return null; + } + return Double.valueOf(str); + } + + /** + *

Convert a String to a Integer, handling + * hex (0xhhhh) and octal (0dddd) notations. + * N.B. a leading zero means octal; spaces are not trimmed.

+ * + *

Returns null if the string is null.

+ * + * @param str a String to convert, may be null + * @return converted Integer (or null if the input is null) + * @throws NumberFormatException if the value cannot be converted + */ +/** + *

Convert a String to a Integer, handling + * hex (0xhhhh) and octal (0dddd) notations. + * N.B. a leading zero means octal; spaces are not trimmed.

+ * + *

Returns null if the string is null.

+ * + * @param str + * a String to convert, may be null + * @return converted Integer (or null if the input is null) + * @throws NumberFormatException + * if the value cannot be converted + */ +public static java.lang.Integer createInteger(final java.lang.String str) { + { + // decode() handles 0xAABD and 0777 (hex and octal) as well. + return java.lang.Integer.decode(/* NPEX_NULL_EXP */ + str); + } +} + + /** + *

Convert a String to a Long; + * since 3.1 it handles hex (0Xhhhh) and octal (0ddd) notations. + * N.B. a leading zero means octal; spaces are not trimmed.

+ * + *

Returns null if the string is null.

+ * + * @param str a String to convert, may be null + * @return converted Long (or null if the input is null) + * @throws NumberFormatException if the value cannot be converted + */ + public static Long createLong(final String str) { + if (str == null) { + return null; + } + return Long.decode(str); + } + + /** + *

Convert a String to a BigInteger; + * since 3.2 it handles hex (0x or #) and octal (0) notations.

+ * + *

Returns null if the string is null.

+ * + * @param str a String to convert, may be null + * @return converted BigInteger (or null if the input is null) + * @throws NumberFormatException if the value cannot be converted + */ + public static BigInteger createBigInteger(final String str) { + if (str == null) { + return null; + } + int pos = 0; // offset within string + int radix = 10; + boolean negate = false; // need to negate later? + if (str.startsWith("-")) { + negate = true; + pos = 1; + } + if (str.startsWith("0x", pos) || str.startsWith("0X", pos)) { // hex + radix = 16; + pos += 2; + } else if (str.startsWith("#", pos)) { // alternative hex (allowed by Long/Integer) + radix = 16; + pos ++; + } else if (str.startsWith("0", pos) && str.length() > pos + 1) { // octal; so long as there are additional digits + radix = 8; + pos ++; + } // default is to treat as decimal + + final BigInteger value = new BigInteger(str.substring(pos), radix); + return negate ? value.negate() : value; + } + + /** + *

Convert a String to a BigDecimal.

+ * + *

Returns null if the string is null.

+ * + * @param str a String to convert, may be null + * @return converted BigDecimal (or null if the input is null) + * @throws NumberFormatException if the value cannot be converted + */ + public static BigDecimal createBigDecimal(final String str) { + if (str == null) { + return null; + } + // handle JDK1.3.1 bug where "" throws IndexOutOfBoundsException + if (StringUtils.isBlank(str)) { + throw new NumberFormatException("A blank string is not a valid number"); + } + if (str.trim().startsWith("--")) { + // this is protection for poorness in java.lang.BigDecimal. + // it accepts this as a legal value, but it does not appear + // to be in specification of class. OS X Java parses it to + // a wrong value. + throw new NumberFormatException(str + " is not a valid number."); + } + return new BigDecimal(str); + } + + // Min in array + //-------------------------------------------------------------------- + /** + *

Returns the minimum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the minimum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @since 3.4 Changed signature from min(long[]) to min(long...) + */ + public static long min(final long... array) { + // Validates input + validateArray(array); + + // Finds and returns min + long min = array[0]; + for (int i = 1; i < array.length; i++) { + if (array[i] < min) { + min = array[i]; + } + } + + return min; + } + + /** + *

Returns the minimum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the minimum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @since 3.4 Changed signature from min(int[]) to min(int...) + */ + public static int min(final int... array) { + // Validates input + validateArray(array); + + // Finds and returns min + int min = array[0]; + for (int j = 1; j < array.length; j++) { + if (array[j] < min) { + min = array[j]; + } + } + + return min; + } + + /** + *

Returns the minimum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the minimum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @since 3.4 Changed signature from min(short[]) to min(short...) + */ + public static short min(final short... array) { + // Validates input + validateArray(array); + + // Finds and returns min + short min = array[0]; + for (int i = 1; i < array.length; i++) { + if (array[i] < min) { + min = array[i]; + } + } + + return min; + } + + /** + *

Returns the minimum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the minimum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @since 3.4 Changed signature from min(byte[]) to min(byte...) + */ + public static byte min(final byte... array) { + // Validates input + validateArray(array); + + // Finds and returns min + byte min = array[0]; + for (int i = 1; i < array.length; i++) { + if (array[i] < min) { + min = array[i]; + } + } + + return min; + } + + /** + *

Returns the minimum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the minimum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @see IEEE754rUtils#min(double[]) IEEE754rUtils for a version of this method that handles NaN differently + * @since 3.4 Changed signature from min(double[]) to min(double...) + */ + public static double min(final double... array) { + // Validates input + validateArray(array); + + // Finds and returns min + double min = array[0]; + for (int i = 1; i < array.length; i++) { + if (Double.isNaN(array[i])) { + return Double.NaN; + } + if (array[i] < min) { + min = array[i]; + } + } + + return min; + } + + /** + *

Returns the minimum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the minimum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @see IEEE754rUtils#min(float[]) IEEE754rUtils for a version of this method that handles NaN differently + * @since 3.4 Changed signature from min(float[]) to min(float...) + */ + public static float min(final float... array) { + // Validates input + validateArray(array); + + // Finds and returns min + float min = array[0]; + for (int i = 1; i < array.length; i++) { + if (Float.isNaN(array[i])) { + return Float.NaN; + } + if (array[i] < min) { + min = array[i]; + } + } + + return min; + } + + // Max in array + //-------------------------------------------------------------------- + /** + *

Returns the maximum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the maximum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @since 3.4 Changed signature from max(long[]) to max(long...) + */ + public static long max(final long... array) { + // Validates input + validateArray(array); + + // Finds and returns max + long max = array[0]; + for (int j = 1; j < array.length; j++) { + if (array[j] > max) { + max = array[j]; + } + } + + return max; + } + + /** + *

Returns the maximum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the maximum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @since 3.4 Changed signature from max(int[]) to max(int...) + */ + public static int max(final int... array) { + // Validates input + validateArray(array); + + // Finds and returns max + int max = array[0]; + for (int j = 1; j < array.length; j++) { + if (array[j] > max) { + max = array[j]; + } + } + + return max; + } + + /** + *

Returns the maximum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the maximum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @since 3.4 Changed signature from max(short[]) to max(short...) + */ + public static short max(final short... array) { + // Validates input + validateArray(array); + + // Finds and returns max + short max = array[0]; + for (int i = 1; i < array.length; i++) { + if (array[i] > max) { + max = array[i]; + } + } + + return max; + } + + /** + *

Returns the maximum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the maximum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @since 3.4 Changed signature from max(byte[]) to max(byte...) + */ + public static byte max(final byte... array) { + // Validates input + validateArray(array); + + // Finds and returns max + byte max = array[0]; + for (int i = 1; i < array.length; i++) { + if (array[i] > max) { + max = array[i]; + } + } + + return max; + } + + /** + *

Returns the maximum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the maximum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @see IEEE754rUtils#max(double[]) IEEE754rUtils for a version of this method that handles NaN differently + * @since 3.4 Changed signature from max(double[]) to max(double...) + */ + public static double max(final double... array) { + // Validates input + validateArray(array); + + // Finds and returns max + double max = array[0]; + for (int j = 1; j < array.length; j++) { + if (Double.isNaN(array[j])) { + return Double.NaN; + } + if (array[j] > max) { + max = array[j]; + } + } + + return max; + } + + /** + *

Returns the maximum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the maximum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @see IEEE754rUtils#max(float[]) IEEE754rUtils for a version of this method that handles NaN differently + * @since 3.4 Changed signature from max(float[]) to max(float...) + */ + public static float max(final float... array) { + // Validates input + validateArray(array); + + // Finds and returns max + float max = array[0]; + for (int j = 1; j < array.length; j++) { + if (Float.isNaN(array[j])) { + return Float.NaN; + } + if (array[j] > max) { + max = array[j]; + } + } + + return max; + } + + /** + * Checks if the specified array is neither null nor empty. + * + * @param array the array to check + * @throws IllegalArgumentException if {@code array} is either {@code null} or empty + */ + private static void validateArray(final Object array) { + if (array == null) { + throw new IllegalArgumentException("The Array must not be null"); + } + Validate.isTrue(Array.getLength(array) != 0, "Array cannot be empty."); + } + + // 3 param min + //----------------------------------------------------------------------- + /** + *

Gets the minimum of three long values.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the smallest of the values + */ + public static long min(long a, final long b, final long c) { + if (b < a) { + a = b; + } + if (c < a) { + a = c; + } + return a; + } + + /** + *

Gets the minimum of three int values.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the smallest of the values + */ + public static int min(int a, final int b, final int c) { + if (b < a) { + a = b; + } + if (c < a) { + a = c; + } + return a; + } + + /** + *

Gets the minimum of three short values.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the smallest of the values + */ + public static short min(short a, final short b, final short c) { + if (b < a) { + a = b; + } + if (c < a) { + a = c; + } + return a; + } + + /** + *

Gets the minimum of three byte values.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the smallest of the values + */ + public static byte min(byte a, final byte b, final byte c) { + if (b < a) { + a = b; + } + if (c < a) { + a = c; + } + return a; + } + + /** + *

Gets the minimum of three double values.

+ * + *

If any value is NaN, NaN is + * returned. Infinity is handled.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the smallest of the values + * @see IEEE754rUtils#min(double, double, double) for a version of this method that handles NaN differently + */ + public static double min(final double a, final double b, final double c) { + return Math.min(Math.min(a, b), c); + } + + /** + *

Gets the minimum of three float values.

+ * + *

If any value is NaN, NaN is + * returned. Infinity is handled.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the smallest of the values + * @see IEEE754rUtils#min(float, float, float) for a version of this method that handles NaN differently + */ + public static float min(final float a, final float b, final float c) { + return Math.min(Math.min(a, b), c); + } + + // 3 param max + //----------------------------------------------------------------------- + /** + *

Gets the maximum of three long values.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the largest of the values + */ + public static long max(long a, final long b, final long c) { + if (b > a) { + a = b; + } + if (c > a) { + a = c; + } + return a; + } + + /** + *

Gets the maximum of three int values.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the largest of the values + */ + public static int max(int a, final int b, final int c) { + if (b > a) { + a = b; + } + if (c > a) { + a = c; + } + return a; + } + + /** + *

Gets the maximum of three short values.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the largest of the values + */ + public static short max(short a, final short b, final short c) { + if (b > a) { + a = b; + } + if (c > a) { + a = c; + } + return a; + } + + /** + *

Gets the maximum of three byte values.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the largest of the values + */ + public static byte max(byte a, final byte b, final byte c) { + if (b > a) { + a = b; + } + if (c > a) { + a = c; + } + return a; + } + + /** + *

Gets the maximum of three double values.

+ * + *

If any value is NaN, NaN is + * returned. Infinity is handled.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the largest of the values + * @see IEEE754rUtils#max(double, double, double) for a version of this method that handles NaN differently + */ + public static double max(final double a, final double b, final double c) { + return Math.max(Math.max(a, b), c); + } + + /** + *

Gets the maximum of three float values.

+ * + *

If any value is NaN, NaN is + * returned. Infinity is handled.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the largest of the values + * @see IEEE754rUtils#max(float, float, float) for a version of this method that handles NaN differently + */ + public static float max(final float a, final float b, final float c) { + return Math.max(Math.max(a, b), c); + } + + //----------------------------------------------------------------------- + /** + *

Checks whether the String contains only + * digit characters.

+ * + *

Null and empty String will return + * false.

+ * + * @param str the String to check + * @return true if str contains only Unicode numeric + */ + public static boolean isDigits(final String str) { + return StringUtils.isNumeric(str); + } + + /** + *

Checks whether the String a valid Java number.

+ * + *

Valid numbers include hexadecimal marked with the 0x or + * 0X qualifier, octal numbers, scientific notation and + * numbers marked with a type qualifier (e.g. 123L).

+ * + *

Non-hexadecimal strings beginning with a leading zero are + * treated as octal values. Thus the string 09 will return + * false, since 9 is not a valid octal value. + * However, numbers beginning with {@code 0.} are treated as decimal.

+ * + *

null and empty/blank {@code String} will return + * false.

+ * + *

Note, {@link #createNumber(String)} should return a number for every + * input resuling in true.

+ * + * @param str the String to check + * @return true if the string is a correctly formatted number + * @since 3.3 the code supports hex {@code 0Xhhh} an + * octal {@code 0ddd} validation + * @deprecated This feature will be removed in Lang 4.0, + * use {@link NumberUtils#isCreatable(String)} instead + */ + @Deprecated + public static boolean isNumber(final String str) { + return isCreatable(str); + } + + /** + *

Checks whether the String a valid Java number.

+ * + *

Valid numbers include hexadecimal marked with the 0x or + * 0X qualifier, octal numbers, scientific notation and + * numbers marked with a type qualifier (e.g. 123L).

+ * + *

Non-hexadecimal strings beginning with a leading zero are + * treated as octal values. Thus the string 09 will return + * false, since 9 is not a valid octal value. + * However, numbers beginning with {@code 0.} are treated as decimal.

+ * + *

null and empty/blank {@code String} will return + * false.

+ * + *

Note, {@link #createNumber(String)} should return a number for every + * input resuling in true.

+ * + * @param str the String to check + * @return true if the string is a correctly formatted number + * @since 3.5 the code supports the "+" suffix on numbers except for integers in Java 1.6 + */ + public static boolean isCreatable(final String str) { + if (StringUtils.isEmpty(str)) { + return false; + } + final char[] chars = str.toCharArray(); + int sz = chars.length; + boolean hasExp = false; + boolean hasDecPoint = false; + boolean allowSigns = false; + boolean foundDigit = false; + // deal with any possible sign up front + final int start = chars[0] == '-' || chars[0] == '+' ? 1 : 0; + final boolean hasLeadingPlusSign = start == 1 && chars[0] == '+'; + if (sz > start + 1 && chars[start] == '0') { // leading 0 + if (chars[start + 1] == 'x' || chars[start + 1] == 'X') { // leading 0x/0X + int i = start + 2; + if (i == sz) { + return false; // str == "0x" + } + // checking hex (it can't be anything else) + for (; i < chars.length; i++) { + if ((chars[i] < '0' || chars[i] > '9') + && (chars[i] < 'a' || chars[i] > 'f') + && (chars[i] < 'A' || chars[i] > 'F')) { + return false; + } + } + return true; + } else if (Character.isDigit(chars[start + 1])) { + // leading 0, but not hex, must be octal + int i = start + 1; + for (; i < chars.length; i++) { + if (chars[i] < '0' || chars[i] > '7') { + return false; + } + } + return true; + } + } + sz--; // don't want to loop to the last char, check it afterwords + // for type qualifiers + int i = start; + // loop to the next to last char or to the last char if we need another digit to + // make a valid number (e.g. chars[0..5] = "1234E") + while (i < sz || i < sz + 1 && allowSigns && !foundDigit) { + if (chars[i] >= '0' && chars[i] <= '9') { + foundDigit = true; + allowSigns = false; + + } else if (chars[i] == '.') { + if (hasDecPoint || hasExp) { + // two decimal points or dec in exponent + return false; + } + hasDecPoint = true; + } else if (chars[i] == 'e' || chars[i] == 'E') { + // we've already taken care of hex. + if (hasExp) { + // two E's + return false; + } + if (!foundDigit) { + return false; + } + hasExp = true; + allowSigns = true; + } else if (chars[i] == '+' || chars[i] == '-') { + if (!allowSigns) { + return false; + } + allowSigns = false; + foundDigit = false; // we need a digit after the E + } else { + return false; + } + i++; + } + if (i < chars.length) { + if (chars[i] >= '0' && chars[i] <= '9') { + if (SystemUtils.IS_JAVA_1_6 && hasLeadingPlusSign && !hasDecPoint) { + return false; + } + // no type qualifier, OK + return true; + } + if (chars[i] == 'e' || chars[i] == 'E') { + // can't have an E at the last byte + return false; + } + if (chars[i] == '.') { + if (hasDecPoint || hasExp) { + // two decimal points or dec in exponent + return false; + } + // single trailing decimal point after non-exponent is ok + return foundDigit; + } + if (!allowSigns + && (chars[i] == 'd' + || chars[i] == 'D' + || chars[i] == 'f' + || chars[i] == 'F')) { + return foundDigit; + } + if (chars[i] == 'l' + || chars[i] == 'L') { + // not allowing L with an exponent or decimal point + return foundDigit && !hasExp && !hasDecPoint; + } + // last character is illegal + return false; + } + // allowSigns is true iff the val ends in 'E' + // found digit it to make sure weird stuff like '.' and '1E-' doesn't pass + return !allowSigns && foundDigit; + } + + /** + *

Checks whether the given String is a parsable number.

+ * + *

Parsable numbers include those Strings understood by {@link Integer#parseInt(String)}, + * {@link Long#parseLong(String)}, {@link Float#parseFloat(String)} or + * {@link Double#parseDouble(String)}. This method can be used instead of catching {@link java.text.ParseException} + * when calling one of those methods.

+ * + *

Hexadecimal and scientific notations are not considered parsable. + * See {@link #isCreatable(String)} on those cases.

+ * + *

{@code Null} and empty String will return false.

+ * + * @param str the String to check. + * @return {@code true} if the string is a parsable number. + * @since 3.4 + */ + public static boolean isParsable(final String str) { + if (StringUtils.isEmpty(str)) { + return false; + } + if (str.charAt(str.length() - 1) == '.') { + return false; + } + if (str.charAt(0) == '-') { + if (str.length() == 1) { + return false; + } + return withDecimalsParsing(str, 1); + } else { + return withDecimalsParsing(str, 0); + } + } + + private static boolean withDecimalsParsing(final String str, final int beginIdx) { + int decimalPoints = 0; + for (int i = beginIdx; i < str.length(); i++) { + final boolean isDecimalPoint = str.charAt(i) == '.'; + if (isDecimalPoint) { + decimalPoints++; + } + if (decimalPoints > 1) { + return false; + } + if (!isDecimalPoint && !Character.isDigit(str.charAt(i))) { + return false; + } + } + return true; + } + + /** + *

Compares two {@code int} values numerically. This is the same functionality as provided in Java 7.

+ * + * @param x the first {@code int} to compare + * @param y the second {@code int} 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(int x, int y) { + if (x == y) { + return 0; + } + return x < y ? -1 : 1; + } + + /** + *

Compares to {@code long} values numerically. This is the same functionality as provided in Java 7.

+ * + * @param x the first {@code long} to compare + * @param y the second {@code long} 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(long x, long y) { + if (x == y) { + return 0; + } + return x < y ? -1 : 1; + } + + /** + *

Compares to {@code short} values numerically. This is the same functionality as provided in Java 7.

+ * + * @param x the first {@code short} to compare + * @param y the second {@code short} 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(short x, short y) { + if (x == y) { + return 0; + } + return x < y ? -1 : 1; + } + + /** + *

Compares two {@code byte} values numerically. This is the same functionality as provided in Java 7.

+ * + * @param x the first {@code byte} to compare + * @param y the second {@code byte} 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(byte x, byte y) { + return x - y; + } +} diff --git a/Java/commons-lang-NumberUtils_713/metadata.json b/Java/commons-lang-NumberUtils_713/metadata.json new file mode 100644 index 000000000..64142120e --- /dev/null +++ b/Java/commons-lang-NumberUtils_713/metadata.json @@ -0,0 +1,21 @@ +{ + "language": "java", + "id": "commons-lang-NumberUtils_713", + "buggyPath": ".", + "referencePath": null, + "buildCommand": "mvn package -V -B -Denforcer.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true -Drat.skip=true -Dlicense.skip=true -Dfindbugs.skip=true -Dgpg.skip=true -Dskip.npm=true -Dskip.gulp=true -Dskip.bower=true -Drat.numUnapprovedLicenses=100 -DskipTests=true -DskipITs=true -Dtest=None -DfailIfNoTests=false", + "testCommand": "mvn test -V -B -Denforcer.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true -Drat.skip=true -Dlicense.skip=true -Dfindbugs.skip=true -Dgpg.skip=true -Dskip.npm=true -Dskip.gulp=true -Dskip.bower=true -Drat.numUnapprovedLicenses=100", + "categories": [ + "safety", + "npe" + ], + "npe": { + "filepath": "src/main/java/org/apache/commons/lang3/math/NumberUtils.java", + "line": 729, + "npe_method": "createInteger", + "deref_field": "str", + "npe_class": "NumberUtils", + "repo": "commons-lang", + "bug_id": "NumberUtils_713" + } +} diff --git a/Java/commons-lang-NumberUtils_713/npe.json b/Java/commons-lang-NumberUtils_713/npe.json new file mode 100644 index 000000000..9c5e255d3 --- /dev/null +++ b/Java/commons-lang-NumberUtils_713/npe.json @@ -0,0 +1,7 @@ +{ + "filepath": "src/main/java/org/apache/commons/lang3/math/NumberUtils.java", + "line": 729, + "npe_method": "createInteger", + "deref_field": "str", + "npe_class": "NumberUtils" +} \ No newline at end of file diff --git a/Java/commons-lang-NumberUtils_732/Dockerfile b/Java/commons-lang-NumberUtils_732/Dockerfile new file mode 100644 index 000000000..7b7fbe349 --- /dev/null +++ b/Java/commons-lang-NumberUtils_732/Dockerfile @@ -0,0 +1,18 @@ +FROM ghcr.io/kupl/starlab-benchmarks/java-base:commons-lang + +ENV TZ=Asia/Seoul + +COPY ./metadata.json . +COPY ./npe.json . +COPY ./buggy.java /tmp/buggy.java +RUN export BUGGY_PATH=$(cat metadata.json | jq -r ".npe.filepath") \ + && export BUGGY_LINE=$(cat metadata.json | jq -r ".npe.line") \ + && export BUGGY_MTHD=$(cat metadata.json | jq -r ".npe.npe_method") \ + && mv /tmp/buggy.java $BUGGY_PATH \ + && echo "[{\"filepath\": \"$BUGGY_PATH\", \"line\": $BUGGY_LINE, \"method_name\": \"$BUGGY_MTHD\"}]" | jq . > traces.json + +RUN git init . && git add -A + +RUN $(cat metadata.json | jq -r ".buildCommand") + +RUN $(cat metadata.json | jq -r ".testCommand"); if [ $? -eq 0 ]; then exit 1; fi diff --git a/Java/commons-lang-NumberUtils_732/buggy.java b/Java/commons-lang-NumberUtils_732/buggy.java new file mode 100644 index 000000000..92afce20f --- /dev/null +++ b/Java/commons-lang-NumberUtils_732/buggy.java @@ -0,0 +1,1646 @@ +/* + * 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 java.lang.reflect.Array; +import java.math.BigDecimal; +import java.math.BigInteger; + +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.SystemUtils; +import org.apache.commons.lang3.Validate; + +/** + *

Provides extra functionality for Java Number classes.

+ * + * @since 2.0 + */ +public class NumberUtils { + + /** Reusable Long constant for zero. */ + public static final Long LONG_ZERO = Long.valueOf(0L); + /** Reusable Long constant for one. */ + public static final Long LONG_ONE = Long.valueOf(1L); + /** Reusable Long constant for minus one. */ + public static final Long LONG_MINUS_ONE = Long.valueOf(-1L); + /** Reusable Integer constant for zero. */ + public static final Integer INTEGER_ZERO = Integer.valueOf(0); + /** Reusable Integer constant for one. */ + public static final Integer INTEGER_ONE = Integer.valueOf(1); + /** Reusable Integer constant for minus one. */ + public static final Integer INTEGER_MINUS_ONE = Integer.valueOf(-1); + /** Reusable Short constant for zero. */ + public static final Short SHORT_ZERO = Short.valueOf((short) 0); + /** Reusable Short constant for one. */ + public static final Short SHORT_ONE = Short.valueOf((short) 1); + /** Reusable Short constant for minus one. */ + public static final Short SHORT_MINUS_ONE = Short.valueOf((short) -1); + /** Reusable Byte constant for zero. */ + public static final Byte BYTE_ZERO = Byte.valueOf((byte) 0); + /** Reusable Byte constant for one. */ + public static final Byte BYTE_ONE = Byte.valueOf((byte) 1); + /** Reusable Byte constant for minus one. */ + public static final Byte BYTE_MINUS_ONE = Byte.valueOf((byte) -1); + /** Reusable Double constant for zero. */ + public static final Double DOUBLE_ZERO = Double.valueOf(0.0d); + /** Reusable Double constant for one. */ + public static final Double DOUBLE_ONE = Double.valueOf(1.0d); + /** Reusable Double constant for minus one. */ + public static final Double DOUBLE_MINUS_ONE = Double.valueOf(-1.0d); + /** Reusable Float constant for zero. */ + public static final Float FLOAT_ZERO = Float.valueOf(0.0f); + /** Reusable Float constant for one. */ + public static final Float FLOAT_ONE = Float.valueOf(1.0f); + /** Reusable Float constant for minus one. */ + public static final Float FLOAT_MINUS_ONE = Float.valueOf(-1.0f); + + /** + *

NumberUtils instances should NOT be constructed in standard programming. + * Instead, the class should be used as NumberUtils.toInt("6");.

+ * + *

This constructor is public to permit tools that require a JavaBean instance + * to operate.

+ */ + public NumberUtils() { + super(); + } + + //----------------------------------------------------------------------- + /** + *

Convert a String to an int, returning + * zero if the conversion fails.

+ * + *

If the string is null, zero is returned.

+ * + *
+     *   NumberUtils.toInt(null) = 0
+     *   NumberUtils.toInt("")   = 0
+     *   NumberUtils.toInt("1")  = 1
+     * 
+ * + * @param str the string to convert, may be null + * @return the int represented by the string, or zero if + * conversion fails + * @since 2.1 + */ + public static int toInt(final String str) { + return toInt(str, 0); + } + + /** + *

Convert a String to an int, returning a + * default value if the conversion fails.

+ * + *

If the string is null, the default value is returned.

+ * + *
+     *   NumberUtils.toInt(null, 1) = 1
+     *   NumberUtils.toInt("", 1)   = 1
+     *   NumberUtils.toInt("1", 0)  = 1
+     * 
+ * + * @param str the string to convert, may be null + * @param defaultValue the default value + * @return the int represented by the string, or the default if conversion fails + * @since 2.1 + */ + public static int toInt(final String str, final int defaultValue) { + if(str == null) { + return defaultValue; + } + try { + return Integer.parseInt(str); + } catch (final NumberFormatException nfe) { + return defaultValue; + } + } + + /** + *

Convert a String to a long, returning + * zero if the conversion fails.

+ * + *

If the string is null, zero is returned.

+ * + *
+     *   NumberUtils.toLong(null) = 0L
+     *   NumberUtils.toLong("")   = 0L
+     *   NumberUtils.toLong("1")  = 1L
+     * 
+ * + * @param str the string to convert, may be null + * @return the long represented by the string, or 0 if + * conversion fails + * @since 2.1 + */ + public static long toLong(final String str) { + return toLong(str, 0L); + } + + /** + *

Convert a String to a long, returning a + * default value if the conversion fails.

+ * + *

If the string is null, the default value is returned.

+ * + *
+     *   NumberUtils.toLong(null, 1L) = 1L
+     *   NumberUtils.toLong("", 1L)   = 1L
+     *   NumberUtils.toLong("1", 0L)  = 1L
+     * 
+ * + * @param str the string to convert, may be null + * @param defaultValue the default value + * @return the long represented by the string, or the default if conversion fails + * @since 2.1 + */ + public static long toLong(final String str, final long defaultValue) { + if (str == null) { + return defaultValue; + } + try { + return Long.parseLong(str); + } catch (final NumberFormatException nfe) { + return defaultValue; + } + } + + /** + *

Convert a String to a float, returning + * 0.0f if the conversion fails.

+ * + *

If the string str is null, + * 0.0f is returned.

+ * + *
+     *   NumberUtils.toFloat(null)   = 0.0f
+     *   NumberUtils.toFloat("")     = 0.0f
+     *   NumberUtils.toFloat("1.5")  = 1.5f
+     * 
+ * + * @param str the string to convert, may be null + * @return the float represented by the string, or 0.0f + * if conversion fails + * @since 2.1 + */ + public static float toFloat(final String str) { + return toFloat(str, 0.0f); + } + + /** + *

Convert a String to a float, returning a + * default value if the conversion fails.

+ * + *

If the string str is null, the default + * value is returned.

+ * + *
+     *   NumberUtils.toFloat(null, 1.1f)   = 1.0f
+     *   NumberUtils.toFloat("", 1.1f)     = 1.1f
+     *   NumberUtils.toFloat("1.5", 0.0f)  = 1.5f
+     * 
+ * + * @param str the string to convert, may be null + * @param defaultValue the default value + * @return the float represented by the string, or defaultValue + * if conversion fails + * @since 2.1 + */ + public static float toFloat(final String str, final float defaultValue) { + if (str == null) { + return defaultValue; + } + try { + return Float.parseFloat(str); + } catch (final NumberFormatException nfe) { + return defaultValue; + } + } + + /** + *

Convert a String to a double, returning + * 0.0d if the conversion fails.

+ * + *

If the string str is null, + * 0.0d is returned.

+ * + *
+     *   NumberUtils.toDouble(null)   = 0.0d
+     *   NumberUtils.toDouble("")     = 0.0d
+     *   NumberUtils.toDouble("1.5")  = 1.5d
+     * 
+ * + * @param str the string to convert, may be null + * @return the double represented by the string, or 0.0d + * if conversion fails + * @since 2.1 + */ + public static double toDouble(final String str) { + return toDouble(str, 0.0d); + } + + /** + *

Convert a String to a double, returning a + * default value if the conversion fails.

+ * + *

If the string str is null, the default + * value is returned.

+ * + *
+     *   NumberUtils.toDouble(null, 1.1d)   = 1.1d
+     *   NumberUtils.toDouble("", 1.1d)     = 1.1d
+     *   NumberUtils.toDouble("1.5", 0.0d)  = 1.5d
+     * 
+ * + * @param str the string to convert, may be null + * @param defaultValue the default value + * @return the double represented by the string, or defaultValue + * if conversion fails + * @since 2.1 + */ + public static double toDouble(final String str, final double defaultValue) { + if (str == null) { + return defaultValue; + } + try { + return Double.parseDouble(str); + } catch (final NumberFormatException nfe) { + return defaultValue; + } + } + + //----------------------------------------------------------------------- + /** + *

Convert a String to a byte, returning + * zero if the conversion fails.

+ * + *

If the string is null, zero is returned.

+ * + *
+     *   NumberUtils.toByte(null) = 0
+     *   NumberUtils.toByte("")   = 0
+     *   NumberUtils.toByte("1")  = 1
+     * 
+ * + * @param str the string to convert, may be null + * @return the byte represented by the string, or zero if + * conversion fails + * @since 2.5 + */ + public static byte toByte(final String str) { + return toByte(str, (byte) 0); + } + + /** + *

Convert a String to a byte, returning a + * default value if the conversion fails.

+ * + *

If the string is null, the default value is returned.

+ * + *
+     *   NumberUtils.toByte(null, 1) = 1
+     *   NumberUtils.toByte("", 1)   = 1
+     *   NumberUtils.toByte("1", 0)  = 1
+     * 
+ * + * @param str the string to convert, may be null + * @param defaultValue the default value + * @return the byte represented by the string, or the default if conversion fails + * @since 2.5 + */ + public static byte toByte(final String str, final byte defaultValue) { + if(str == null) { + return defaultValue; + } + try { + return Byte.parseByte(str); + } catch (final NumberFormatException nfe) { + return defaultValue; + } + } + + /** + *

Convert a String to a short, returning + * zero if the conversion fails.

+ * + *

If the string is null, zero is returned.

+ * + *
+     *   NumberUtils.toShort(null) = 0
+     *   NumberUtils.toShort("")   = 0
+     *   NumberUtils.toShort("1")  = 1
+     * 
+ * + * @param str the string to convert, may be null + * @return the short represented by the string, or zero if + * conversion fails + * @since 2.5 + */ + public static short toShort(final String str) { + return toShort(str, (short) 0); + } + + /** + *

Convert a String to an short, returning a + * default value if the conversion fails.

+ * + *

If the string is null, the default value is returned.

+ * + *
+     *   NumberUtils.toShort(null, 1) = 1
+     *   NumberUtils.toShort("", 1)   = 1
+     *   NumberUtils.toShort("1", 0)  = 1
+     * 
+ * + * @param str the string to convert, may be null + * @param defaultValue the default value + * @return the short represented by the string, or the default if conversion fails + * @since 2.5 + */ + public static short toShort(final String str, final short defaultValue) { + if(str == null) { + return defaultValue; + } + try { + return Short.parseShort(str); + } catch (final NumberFormatException nfe) { + return defaultValue; + } + } + + //----------------------------------------------------------------------- + // must handle Long, Float, Integer, Float, Short, + // BigDecimal, BigInteger and Byte + // useful methods: + // Byte.decode(String) + // Byte.valueOf(String,int radix) + // Byte.valueOf(String) + // Double.valueOf(String) + // Float.valueOf(String) + // Float.valueOf(String) + // Integer.valueOf(String,int radix) + // Integer.valueOf(String) + // Integer.decode(String) + // Integer.getInteger(String) + // Integer.getInteger(String,int val) + // Integer.getInteger(String,Integer val) + // Integer.valueOf(String) + // Double.valueOf(String) + // new Byte(String) + // Long.valueOf(String) + // Long.getLong(String) + // Long.getLong(String,int) + // Long.getLong(String,Integer) + // Long.valueOf(String,int) + // Long.valueOf(String) + // Short.valueOf(String) + // Short.decode(String) + // Short.valueOf(String,int) + // Short.valueOf(String) + // new BigDecimal(String) + // new BigInteger(String) + // new BigInteger(String,int radix) + // Possible inputs: + // 45 45.5 45E7 4.5E7 Hex Oct Binary xxxF xxxD xxxf xxxd + // plus minus everything. Prolly more. A lot are not separable. + + /** + *

Turns a string value into a java.lang.Number.

+ * + *

If the string starts with {@code 0x} or {@code -0x} (lower or upper case) or {@code #} or {@code -#}, it + * will be interpreted as a hexadecimal Integer - or Long, if the number of digits after the + * prefix is more than 8 - or BigInteger if there are more than 16 digits. + *

+ *

Then, the value is examined for a type qualifier on the end, i.e. one of + * 'f','F','d','D','l','L'. If it is found, it starts + * trying to create successively larger types from the type specified + * until one is found that can represent the value.

+ * + *

If a type specifier is not found, it will check for a decimal point + * and then try successively larger types from Integer to + * BigInteger and from Float to + * BigDecimal.

+ * + *

+ * Integral values with a leading {@code 0} will be interpreted as octal; the returned number will + * be Integer, Long or BigDecimal as appropriate. + *

+ * + *

Returns null if the string is null.

+ * + *

This method does not trim the input string, i.e., strings with leading + * or trailing spaces will generate NumberFormatExceptions.

+ * + * @param str String containing a number, may be null + * @return Number created from the string (or null if the input is null) + * @throws NumberFormatException if the value cannot be converted + */ + public static Number createNumber(final String str) throws NumberFormatException { + if (str == null) { + return null; + } + if (StringUtils.isBlank(str)) { + throw new NumberFormatException("A blank string is not a valid number"); + } + // Need to deal with all possible hex prefixes here + final String[] hex_prefixes = {"0x", "0X", "-0x", "-0X", "#", "-#"}; + int pfxLen = 0; + for(final String pfx : hex_prefixes) { + if (str.startsWith(pfx)) { + pfxLen += pfx.length(); + break; + } + } + if (pfxLen > 0) { // we have a hex number + char firstSigDigit = 0; // strip leading zeroes + for(int i = pfxLen; i < str.length(); i++) { + firstSigDigit = str.charAt(i); + if (firstSigDigit == '0') { // count leading zeroes + pfxLen++; + } else { + break; + } + } + final int hexDigits = str.length() - pfxLen; + if (hexDigits > 16 || hexDigits == 16 && firstSigDigit > '7') { // too many for Long + return createBigInteger(str); + } + if (hexDigits > 8 || hexDigits == 8 && firstSigDigit > '7') { // too many for an int + return createLong(str); + } + return createInteger(str); + } + final char lastChar = str.charAt(str.length() - 1); + String mant; + String dec; + String exp; + final int decPos = str.indexOf('.'); + final int expPos = str.indexOf('e') + str.indexOf('E') + 1; // assumes both not present + // if both e and E are present, this is caught by the checks on expPos (which prevent IOOBE) + // and the parsing which will detect if e or E appear in a number due to using the wrong offset + + if (decPos > -1) { // there is a decimal point + if (expPos > -1) { // there is an exponent + if (expPos < decPos || expPos > str.length()) { // prevents double exponent causing IOOBE + throw new NumberFormatException(str + " is not a valid number."); + } + dec = str.substring(decPos + 1, expPos); + } else { + dec = str.substring(decPos + 1); + } + mant = getMantissa(str, decPos); + } else { + if (expPos > -1) { + if (expPos > str.length()) { // prevents double exponent causing IOOBE + throw new NumberFormatException(str + " is not a valid number."); + } + mant = getMantissa(str, expPos); + } else { + mant = getMantissa(str); + } + dec = null; + } + if (!Character.isDigit(lastChar) && lastChar != '.') { + if (expPos > -1 && expPos < str.length() - 1) { + exp = str.substring(expPos + 1, str.length() - 1); + } else { + exp = null; + } + //Requesting a specific type.. + final String numeric = str.substring(0, str.length() - 1); + final boolean allZeros = isAllZeros(mant) && isAllZeros(exp); + switch (lastChar) { + case 'l' : + case 'L' : + if (dec == null + && exp == null + && (numeric.charAt(0) == '-' && isDigits(numeric.substring(1)) || isDigits(numeric))) { + try { + return createLong(numeric); + } catch (final NumberFormatException nfe) { // NOPMD + // Too big for a long + } + return createBigInteger(numeric); + + } + throw new NumberFormatException(str + " is not a valid number."); + case 'f' : + case 'F' : + try { + final Float f = NumberUtils.createFloat(str); + if (!(f.isInfinite() || f.floatValue() == 0.0F && !allZeros)) { + //If it's too big for a float or the float value = 0 and the string + //has non-zeros in it, then float does not have the precision we want + return f; + } + + } catch (final NumberFormatException nfe) { // NOPMD + // ignore the bad number + } + //$FALL-THROUGH$ + case 'd' : + case 'D' : + try { + final Double d = NumberUtils.createDouble(str); + if (!(d.isInfinite() || d.floatValue() == 0.0D && !allZeros)) { + return d; + } + } catch (final NumberFormatException nfe) { // NOPMD + // ignore the bad number + } + try { + return createBigDecimal(numeric); + } catch (final NumberFormatException e) { // NOPMD + // ignore the bad number + } + //$FALL-THROUGH$ + default : + throw new NumberFormatException(str + " is not a valid number."); + + } + } + //User doesn't have a preference on the return type, so let's start + //small and go from there... + if (expPos > -1 && expPos < str.length() - 1) { + exp = str.substring(expPos + 1, str.length()); + } else { + exp = null; + } + if (dec == null && exp == null) { // no decimal point and no exponent + //Must be an Integer, Long, Biginteger + try { + return createInteger(str); + } catch (final NumberFormatException nfe) { // NOPMD + // ignore the bad number + } + try { + return createLong(str); + } catch (final NumberFormatException nfe) { // NOPMD + // ignore the bad number + } + return createBigInteger(str); + } + + //Must be a Float, Double, BigDecimal + final boolean allZeros = isAllZeros(mant) && isAllZeros(exp); + try { + final Float f = createFloat(str); + final Double d = createDouble(str); + if (!f.isInfinite() + && !(f.floatValue() == 0.0F && !allZeros) + && f.toString().equals(d.toString())) { + return f; + } + if (!d.isInfinite() && !(d.doubleValue() == 0.0D && !allZeros)) { + final BigDecimal b = createBigDecimal(str); + if (b.compareTo(BigDecimal.valueOf(d)) == 0) { + return d; + } + return b; + } + } catch (final NumberFormatException nfe) { // NOPMD + // ignore the bad number + } + return createBigDecimal(str); + } + + /** + *

Utility method for {@link #createNumber(java.lang.String)}.

+ * + *

Returns mantissa of the given number.

+ * + * @param str the string representation of the number + * @return mantissa of the given number + */ + private static String getMantissa(final String str) { + return getMantissa(str, str.length()); + } + + /** + *

Utility method for {@link #createNumber(java.lang.String)}.

+ * + *

Returns mantissa of the given number.

+ * + * @param str the string representation of the number + * @param stopPos the position of the exponent or decimal point + * @return mantissa of the given number + */ + private static String getMantissa(final String str, final int stopPos) { + final char firstChar = str.charAt(0); + final boolean hasSign = firstChar == '-' || firstChar == '+'; + + return hasSign ? str.substring(1, stopPos) : str.substring(0, stopPos); + } + + /** + *

Utility method for {@link #createNumber(java.lang.String)}.

+ * + *

Returns true if s is null.

+ * + * @param str the String to check + * @return if it is all zeros or null + */ + private static boolean isAllZeros(final String str) { + if (str == null) { + return true; + } + for (int i = str.length() - 1; i >= 0; i--) { + if (str.charAt(i) != '0') { + return false; + } + } + return str.length() > 0; + } + + //----------------------------------------------------------------------- + /** + *

Convert a String to a Float.

+ * + *

Returns null if the string is null.

+ * + * @param str a String to convert, may be null + * @return converted Float (or null if the input is null) + * @throws NumberFormatException if the value cannot be converted + */ + public static Float createFloat(final String str) { + if (str == null) { + return null; + } + return Float.valueOf(str); + } + + /** + *

Convert a String to a Double.

+ * + *

Returns null if the string is null.

+ * + * @param str a String to convert, may be null + * @return converted Double (or null if the input is null) + * @throws NumberFormatException if the value cannot be converted + */ + public static Double createDouble(final String str) { + if (str == null) { + return null; + } + return Double.valueOf(str); + } + + /** + *

Convert a String to a Integer, handling + * hex (0xhhhh) and octal (0dddd) notations. + * N.B. a leading zero means octal; spaces are not trimmed.

+ * + *

Returns null if the string is null.

+ * + * @param str a String to convert, may be null + * @return converted Integer (or null if the input is null) + * @throws NumberFormatException if the value cannot be converted + */ + public static Integer createInteger(final String str) { + if (str == null) { + return null; + } + // decode() handles 0xAABD and 0777 (hex and octal) as well. + return Integer.decode(str); + } + + /** + *

Convert a String to a Long; + * since 3.1 it handles hex (0Xhhhh) and octal (0ddd) notations. + * N.B. a leading zero means octal; spaces are not trimmed.

+ * + *

Returns null if the string is null.

+ * + * @param str a String to convert, may be null + * @return converted Long (or null if the input is null) + * @throws NumberFormatException if the value cannot be converted + */ +/** + *

Convert a String to a Long; + * since 3.1 it handles hex (0Xhhhh) and octal (0ddd) notations. + * N.B. a leading zero means octal; spaces are not trimmed.

+ * + *

Returns null if the string is null.

+ * + * @param str + * a String to convert, may be null + * @return converted Long (or null if the input is null) + * @throws NumberFormatException + * if the value cannot be converted + */ +public static java.lang.Long createLong(final java.lang.String str) { + { + return java.lang.Long.decode(/* NPEX_NULL_EXP */ + str); + } +} + + /** + *

Convert a String to a BigInteger; + * since 3.2 it handles hex (0x or #) and octal (0) notations.

+ * + *

Returns null if the string is null.

+ * + * @param str a String to convert, may be null + * @return converted BigInteger (or null if the input is null) + * @throws NumberFormatException if the value cannot be converted + */ + public static BigInteger createBigInteger(final String str) { + if (str == null) { + return null; + } + int pos = 0; // offset within string + int radix = 10; + boolean negate = false; // need to negate later? + if (str.startsWith("-")) { + negate = true; + pos = 1; + } + if (str.startsWith("0x", pos) || str.startsWith("0X", pos)) { // hex + radix = 16; + pos += 2; + } else if (str.startsWith("#", pos)) { // alternative hex (allowed by Long/Integer) + radix = 16; + pos ++; + } else if (str.startsWith("0", pos) && str.length() > pos + 1) { // octal; so long as there are additional digits + radix = 8; + pos ++; + } // default is to treat as decimal + + final BigInteger value = new BigInteger(str.substring(pos), radix); + return negate ? value.negate() : value; + } + + /** + *

Convert a String to a BigDecimal.

+ * + *

Returns null if the string is null.

+ * + * @param str a String to convert, may be null + * @return converted BigDecimal (or null if the input is null) + * @throws NumberFormatException if the value cannot be converted + */ + public static BigDecimal createBigDecimal(final String str) { + if (str == null) { + return null; + } + // handle JDK1.3.1 bug where "" throws IndexOutOfBoundsException + if (StringUtils.isBlank(str)) { + throw new NumberFormatException("A blank string is not a valid number"); + } + if (str.trim().startsWith("--")) { + // this is protection for poorness in java.lang.BigDecimal. + // it accepts this as a legal value, but it does not appear + // to be in specification of class. OS X Java parses it to + // a wrong value. + throw new NumberFormatException(str + " is not a valid number."); + } + return new BigDecimal(str); + } + + // Min in array + //-------------------------------------------------------------------- + /** + *

Returns the minimum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the minimum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @since 3.4 Changed signature from min(long[]) to min(long...) + */ + public static long min(final long... array) { + // Validates input + validateArray(array); + + // Finds and returns min + long min = array[0]; + for (int i = 1; i < array.length; i++) { + if (array[i] < min) { + min = array[i]; + } + } + + return min; + } + + /** + *

Returns the minimum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the minimum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @since 3.4 Changed signature from min(int[]) to min(int...) + */ + public static int min(final int... array) { + // Validates input + validateArray(array); + + // Finds and returns min + int min = array[0]; + for (int j = 1; j < array.length; j++) { + if (array[j] < min) { + min = array[j]; + } + } + + return min; + } + + /** + *

Returns the minimum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the minimum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @since 3.4 Changed signature from min(short[]) to min(short...) + */ + public static short min(final short... array) { + // Validates input + validateArray(array); + + // Finds and returns min + short min = array[0]; + for (int i = 1; i < array.length; i++) { + if (array[i] < min) { + min = array[i]; + } + } + + return min; + } + + /** + *

Returns the minimum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the minimum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @since 3.4 Changed signature from min(byte[]) to min(byte...) + */ + public static byte min(final byte... array) { + // Validates input + validateArray(array); + + // Finds and returns min + byte min = array[0]; + for (int i = 1; i < array.length; i++) { + if (array[i] < min) { + min = array[i]; + } + } + + return min; + } + + /** + *

Returns the minimum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the minimum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @see IEEE754rUtils#min(double[]) IEEE754rUtils for a version of this method that handles NaN differently + * @since 3.4 Changed signature from min(double[]) to min(double...) + */ + public static double min(final double... array) { + // Validates input + validateArray(array); + + // Finds and returns min + double min = array[0]; + for (int i = 1; i < array.length; i++) { + if (Double.isNaN(array[i])) { + return Double.NaN; + } + if (array[i] < min) { + min = array[i]; + } + } + + return min; + } + + /** + *

Returns the minimum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the minimum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @see IEEE754rUtils#min(float[]) IEEE754rUtils for a version of this method that handles NaN differently + * @since 3.4 Changed signature from min(float[]) to min(float...) + */ + public static float min(final float... array) { + // Validates input + validateArray(array); + + // Finds and returns min + float min = array[0]; + for (int i = 1; i < array.length; i++) { + if (Float.isNaN(array[i])) { + return Float.NaN; + } + if (array[i] < min) { + min = array[i]; + } + } + + return min; + } + + // Max in array + //-------------------------------------------------------------------- + /** + *

Returns the maximum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the maximum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @since 3.4 Changed signature from max(long[]) to max(long...) + */ + public static long max(final long... array) { + // Validates input + validateArray(array); + + // Finds and returns max + long max = array[0]; + for (int j = 1; j < array.length; j++) { + if (array[j] > max) { + max = array[j]; + } + } + + return max; + } + + /** + *

Returns the maximum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the maximum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @since 3.4 Changed signature from max(int[]) to max(int...) + */ + public static int max(final int... array) { + // Validates input + validateArray(array); + + // Finds and returns max + int max = array[0]; + for (int j = 1; j < array.length; j++) { + if (array[j] > max) { + max = array[j]; + } + } + + return max; + } + + /** + *

Returns the maximum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the maximum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @since 3.4 Changed signature from max(short[]) to max(short...) + */ + public static short max(final short... array) { + // Validates input + validateArray(array); + + // Finds and returns max + short max = array[0]; + for (int i = 1; i < array.length; i++) { + if (array[i] > max) { + max = array[i]; + } + } + + return max; + } + + /** + *

Returns the maximum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the maximum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @since 3.4 Changed signature from max(byte[]) to max(byte...) + */ + public static byte max(final byte... array) { + // Validates input + validateArray(array); + + // Finds and returns max + byte max = array[0]; + for (int i = 1; i < array.length; i++) { + if (array[i] > max) { + max = array[i]; + } + } + + return max; + } + + /** + *

Returns the maximum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the maximum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @see IEEE754rUtils#max(double[]) IEEE754rUtils for a version of this method that handles NaN differently + * @since 3.4 Changed signature from max(double[]) to max(double...) + */ + public static double max(final double... array) { + // Validates input + validateArray(array); + + // Finds and returns max + double max = array[0]; + for (int j = 1; j < array.length; j++) { + if (Double.isNaN(array[j])) { + return Double.NaN; + } + if (array[j] > max) { + max = array[j]; + } + } + + return max; + } + + /** + *

Returns the maximum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the maximum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @see IEEE754rUtils#max(float[]) IEEE754rUtils for a version of this method that handles NaN differently + * @since 3.4 Changed signature from max(float[]) to max(float...) + */ + public static float max(final float... array) { + // Validates input + validateArray(array); + + // Finds and returns max + float max = array[0]; + for (int j = 1; j < array.length; j++) { + if (Float.isNaN(array[j])) { + return Float.NaN; + } + if (array[j] > max) { + max = array[j]; + } + } + + return max; + } + + /** + * Checks if the specified array is neither null nor empty. + * + * @param array the array to check + * @throws IllegalArgumentException if {@code array} is either {@code null} or empty + */ + private static void validateArray(final Object array) { + if (array == null) { + throw new IllegalArgumentException("The Array must not be null"); + } + Validate.isTrue(Array.getLength(array) != 0, "Array cannot be empty."); + } + + // 3 param min + //----------------------------------------------------------------------- + /** + *

Gets the minimum of three long values.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the smallest of the values + */ + public static long min(long a, final long b, final long c) { + if (b < a) { + a = b; + } + if (c < a) { + a = c; + } + return a; + } + + /** + *

Gets the minimum of three int values.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the smallest of the values + */ + public static int min(int a, final int b, final int c) { + if (b < a) { + a = b; + } + if (c < a) { + a = c; + } + return a; + } + + /** + *

Gets the minimum of three short values.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the smallest of the values + */ + public static short min(short a, final short b, final short c) { + if (b < a) { + a = b; + } + if (c < a) { + a = c; + } + return a; + } + + /** + *

Gets the minimum of three byte values.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the smallest of the values + */ + public static byte min(byte a, final byte b, final byte c) { + if (b < a) { + a = b; + } + if (c < a) { + a = c; + } + return a; + } + + /** + *

Gets the minimum of three double values.

+ * + *

If any value is NaN, NaN is + * returned. Infinity is handled.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the smallest of the values + * @see IEEE754rUtils#min(double, double, double) for a version of this method that handles NaN differently + */ + public static double min(final double a, final double b, final double c) { + return Math.min(Math.min(a, b), c); + } + + /** + *

Gets the minimum of three float values.

+ * + *

If any value is NaN, NaN is + * returned. Infinity is handled.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the smallest of the values + * @see IEEE754rUtils#min(float, float, float) for a version of this method that handles NaN differently + */ + public static float min(final float a, final float b, final float c) { + return Math.min(Math.min(a, b), c); + } + + // 3 param max + //----------------------------------------------------------------------- + /** + *

Gets the maximum of three long values.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the largest of the values + */ + public static long max(long a, final long b, final long c) { + if (b > a) { + a = b; + } + if (c > a) { + a = c; + } + return a; + } + + /** + *

Gets the maximum of three int values.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the largest of the values + */ + public static int max(int a, final int b, final int c) { + if (b > a) { + a = b; + } + if (c > a) { + a = c; + } + return a; + } + + /** + *

Gets the maximum of three short values.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the largest of the values + */ + public static short max(short a, final short b, final short c) { + if (b > a) { + a = b; + } + if (c > a) { + a = c; + } + return a; + } + + /** + *

Gets the maximum of three byte values.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the largest of the values + */ + public static byte max(byte a, final byte b, final byte c) { + if (b > a) { + a = b; + } + if (c > a) { + a = c; + } + return a; + } + + /** + *

Gets the maximum of three double values.

+ * + *

If any value is NaN, NaN is + * returned. Infinity is handled.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the largest of the values + * @see IEEE754rUtils#max(double, double, double) for a version of this method that handles NaN differently + */ + public static double max(final double a, final double b, final double c) { + return Math.max(Math.max(a, b), c); + } + + /** + *

Gets the maximum of three float values.

+ * + *

If any value is NaN, NaN is + * returned. Infinity is handled.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the largest of the values + * @see IEEE754rUtils#max(float, float, float) for a version of this method that handles NaN differently + */ + public static float max(final float a, final float b, final float c) { + return Math.max(Math.max(a, b), c); + } + + //----------------------------------------------------------------------- + /** + *

Checks whether the String contains only + * digit characters.

+ * + *

Null and empty String will return + * false.

+ * + * @param str the String to check + * @return true if str contains only Unicode numeric + */ + public static boolean isDigits(final String str) { + return StringUtils.isNumeric(str); + } + + /** + *

Checks whether the String a valid Java number.

+ * + *

Valid numbers include hexadecimal marked with the 0x or + * 0X qualifier, octal numbers, scientific notation and + * numbers marked with a type qualifier (e.g. 123L).

+ * + *

Non-hexadecimal strings beginning with a leading zero are + * treated as octal values. Thus the string 09 will return + * false, since 9 is not a valid octal value. + * However, numbers beginning with {@code 0.} are treated as decimal.

+ * + *

null and empty/blank {@code String} will return + * false.

+ * + *

Note, {@link #createNumber(String)} should return a number for every + * input resuling in true.

+ * + * @param str the String to check + * @return true if the string is a correctly formatted number + * @since 3.3 the code supports hex {@code 0Xhhh} an + * octal {@code 0ddd} validation + * @deprecated This feature will be removed in Lang 4.0, + * use {@link NumberUtils#isCreatable(String)} instead + */ + @Deprecated + public static boolean isNumber(final String str) { + return isCreatable(str); + } + + /** + *

Checks whether the String a valid Java number.

+ * + *

Valid numbers include hexadecimal marked with the 0x or + * 0X qualifier, octal numbers, scientific notation and + * numbers marked with a type qualifier (e.g. 123L).

+ * + *

Non-hexadecimal strings beginning with a leading zero are + * treated as octal values. Thus the string 09 will return + * false, since 9 is not a valid octal value. + * However, numbers beginning with {@code 0.} are treated as decimal.

+ * + *

null and empty/blank {@code String} will return + * false.

+ * + *

Note, {@link #createNumber(String)} should return a number for every + * input resuling in true.

+ * + * @param str the String to check + * @return true if the string is a correctly formatted number + * @since 3.5 the code supports the "+" suffix on numbers except for integers in Java 1.6 + */ + public static boolean isCreatable(final String str) { + if (StringUtils.isEmpty(str)) { + return false; + } + final char[] chars = str.toCharArray(); + int sz = chars.length; + boolean hasExp = false; + boolean hasDecPoint = false; + boolean allowSigns = false; + boolean foundDigit = false; + // deal with any possible sign up front + final int start = chars[0] == '-' || chars[0] == '+' ? 1 : 0; + final boolean hasLeadingPlusSign = start == 1 && chars[0] == '+'; + if (sz > start + 1 && chars[start] == '0') { // leading 0 + if (chars[start + 1] == 'x' || chars[start + 1] == 'X') { // leading 0x/0X + int i = start + 2; + if (i == sz) { + return false; // str == "0x" + } + // checking hex (it can't be anything else) + for (; i < chars.length; i++) { + if ((chars[i] < '0' || chars[i] > '9') + && (chars[i] < 'a' || chars[i] > 'f') + && (chars[i] < 'A' || chars[i] > 'F')) { + return false; + } + } + return true; + } else if (Character.isDigit(chars[start + 1])) { + // leading 0, but not hex, must be octal + int i = start + 1; + for (; i < chars.length; i++) { + if (chars[i] < '0' || chars[i] > '7') { + return false; + } + } + return true; + } + } + sz--; // don't want to loop to the last char, check it afterwords + // for type qualifiers + int i = start; + // loop to the next to last char or to the last char if we need another digit to + // make a valid number (e.g. chars[0..5] = "1234E") + while (i < sz || i < sz + 1 && allowSigns && !foundDigit) { + if (chars[i] >= '0' && chars[i] <= '9') { + foundDigit = true; + allowSigns = false; + + } else if (chars[i] == '.') { + if (hasDecPoint || hasExp) { + // two decimal points or dec in exponent + return false; + } + hasDecPoint = true; + } else if (chars[i] == 'e' || chars[i] == 'E') { + // we've already taken care of hex. + if (hasExp) { + // two E's + return false; + } + if (!foundDigit) { + return false; + } + hasExp = true; + allowSigns = true; + } else if (chars[i] == '+' || chars[i] == '-') { + if (!allowSigns) { + return false; + } + allowSigns = false; + foundDigit = false; // we need a digit after the E + } else { + return false; + } + i++; + } + if (i < chars.length) { + if (chars[i] >= '0' && chars[i] <= '9') { + if (SystemUtils.IS_JAVA_1_6 && hasLeadingPlusSign && !hasDecPoint) { + return false; + } + // no type qualifier, OK + return true; + } + if (chars[i] == 'e' || chars[i] == 'E') { + // can't have an E at the last byte + return false; + } + if (chars[i] == '.') { + if (hasDecPoint || hasExp) { + // two decimal points or dec in exponent + return false; + } + // single trailing decimal point after non-exponent is ok + return foundDigit; + } + if (!allowSigns + && (chars[i] == 'd' + || chars[i] == 'D' + || chars[i] == 'f' + || chars[i] == 'F')) { + return foundDigit; + } + if (chars[i] == 'l' + || chars[i] == 'L') { + // not allowing L with an exponent or decimal point + return foundDigit && !hasExp && !hasDecPoint; + } + // last character is illegal + return false; + } + // allowSigns is true iff the val ends in 'E' + // found digit it to make sure weird stuff like '.' and '1E-' doesn't pass + return !allowSigns && foundDigit; + } + + /** + *

Checks whether the given String is a parsable number.

+ * + *

Parsable numbers include those Strings understood by {@link Integer#parseInt(String)}, + * {@link Long#parseLong(String)}, {@link Float#parseFloat(String)} or + * {@link Double#parseDouble(String)}. This method can be used instead of catching {@link java.text.ParseException} + * when calling one of those methods.

+ * + *

Hexadecimal and scientific notations are not considered parsable. + * See {@link #isCreatable(String)} on those cases.

+ * + *

{@code Null} and empty String will return false.

+ * + * @param str the String to check. + * @return {@code true} if the string is a parsable number. + * @since 3.4 + */ + public static boolean isParsable(final String str) { + if (StringUtils.isEmpty(str)) { + return false; + } + if (str.charAt(str.length() - 1) == '.') { + return false; + } + if (str.charAt(0) == '-') { + if (str.length() == 1) { + return false; + } + return withDecimalsParsing(str, 1); + } else { + return withDecimalsParsing(str, 0); + } + } + + private static boolean withDecimalsParsing(final String str, final int beginIdx) { + int decimalPoints = 0; + for (int i = beginIdx; i < str.length(); i++) { + final boolean isDecimalPoint = str.charAt(i) == '.'; + if (isDecimalPoint) { + decimalPoints++; + } + if (decimalPoints > 1) { + return false; + } + if (!isDecimalPoint && !Character.isDigit(str.charAt(i))) { + return false; + } + } + return true; + } + + /** + *

Compares two {@code int} values numerically. This is the same functionality as provided in Java 7.

+ * + * @param x the first {@code int} to compare + * @param y the second {@code int} 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(int x, int y) { + if (x == y) { + return 0; + } + return x < y ? -1 : 1; + } + + /** + *

Compares to {@code long} values numerically. This is the same functionality as provided in Java 7.

+ * + * @param x the first {@code long} to compare + * @param y the second {@code long} 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(long x, long y) { + if (x == y) { + return 0; + } + return x < y ? -1 : 1; + } + + /** + *

Compares to {@code short} values numerically. This is the same functionality as provided in Java 7.

+ * + * @param x the first {@code short} to compare + * @param y the second {@code short} 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(short x, short y) { + if (x == y) { + return 0; + } + return x < y ? -1 : 1; + } + + /** + *

Compares two {@code byte} values numerically. This is the same functionality as provided in Java 7.

+ * + * @param x the first {@code byte} to compare + * @param y the second {@code byte} 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(byte x, byte y) { + return x - y; + } +} diff --git a/Java/commons-lang-NumberUtils_732/metadata.json b/Java/commons-lang-NumberUtils_732/metadata.json new file mode 100644 index 000000000..b559cdec2 --- /dev/null +++ b/Java/commons-lang-NumberUtils_732/metadata.json @@ -0,0 +1,21 @@ +{ + "language": "java", + "id": "commons-lang-NumberUtils_732", + "buggyPath": ".", + "referencePath": null, + "buildCommand": "mvn package -V -B -Denforcer.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true -Drat.skip=true -Dlicense.skip=true -Dfindbugs.skip=true -Dgpg.skip=true -Dskip.npm=true -Dskip.gulp=true -Dskip.bower=true -Drat.numUnapprovedLicenses=100 -DskipTests=true -DskipITs=true -Dtest=None -DfailIfNoTests=false", + "testCommand": "mvn test -V -B -Denforcer.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true -Drat.skip=true -Dlicense.skip=true -Dfindbugs.skip=true -Dgpg.skip=true -Dskip.npm=true -Dskip.gulp=true -Dskip.bower=true -Drat.numUnapprovedLicenses=100", + "categories": [ + "safety", + "npe" + ], + "npe": { + "filepath": "src/main/java/org/apache/commons/lang3/math/NumberUtils.java", + "line": 747, + "npe_method": "createLong", + "deref_field": "str", + "npe_class": "NumberUtils", + "repo": "commons-lang", + "bug_id": "NumberUtils_732" + } +} diff --git a/Java/commons-lang-NumberUtils_732/npe.json b/Java/commons-lang-NumberUtils_732/npe.json new file mode 100644 index 000000000..6446628ef --- /dev/null +++ b/Java/commons-lang-NumberUtils_732/npe.json @@ -0,0 +1,7 @@ +{ + "filepath": "src/main/java/org/apache/commons/lang3/math/NumberUtils.java", + "line": 747, + "npe_method": "createLong", + "deref_field": "str", + "npe_class": "NumberUtils" +} \ No newline at end of file diff --git a/Java/commons-lang-NumberUtils_749/Dockerfile b/Java/commons-lang-NumberUtils_749/Dockerfile new file mode 100644 index 000000000..7b7fbe349 --- /dev/null +++ b/Java/commons-lang-NumberUtils_749/Dockerfile @@ -0,0 +1,18 @@ +FROM ghcr.io/kupl/starlab-benchmarks/java-base:commons-lang + +ENV TZ=Asia/Seoul + +COPY ./metadata.json . +COPY ./npe.json . +COPY ./buggy.java /tmp/buggy.java +RUN export BUGGY_PATH=$(cat metadata.json | jq -r ".npe.filepath") \ + && export BUGGY_LINE=$(cat metadata.json | jq -r ".npe.line") \ + && export BUGGY_MTHD=$(cat metadata.json | jq -r ".npe.npe_method") \ + && mv /tmp/buggy.java $BUGGY_PATH \ + && echo "[{\"filepath\": \"$BUGGY_PATH\", \"line\": $BUGGY_LINE, \"method_name\": \"$BUGGY_MTHD\"}]" | jq . > traces.json + +RUN git init . && git add -A + +RUN $(cat metadata.json | jq -r ".buildCommand") + +RUN $(cat metadata.json | jq -r ".testCommand"); if [ $? -eq 0 ]; then exit 1; fi diff --git a/Java/commons-lang-NumberUtils_749/buggy.java b/Java/commons-lang-NumberUtils_749/buggy.java new file mode 100644 index 000000000..71518ff06 --- /dev/null +++ b/Java/commons-lang-NumberUtils_749/buggy.java @@ -0,0 +1,1651 @@ +/* + * 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 java.lang.reflect.Array; +import java.math.BigDecimal; +import java.math.BigInteger; + +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.SystemUtils; +import org.apache.commons.lang3.Validate; + +/** + *

Provides extra functionality for Java Number classes.

+ * + * @since 2.0 + */ +public class NumberUtils { + + /** Reusable Long constant for zero. */ + public static final Long LONG_ZERO = Long.valueOf(0L); + /** Reusable Long constant for one. */ + public static final Long LONG_ONE = Long.valueOf(1L); + /** Reusable Long constant for minus one. */ + public static final Long LONG_MINUS_ONE = Long.valueOf(-1L); + /** Reusable Integer constant for zero. */ + public static final Integer INTEGER_ZERO = Integer.valueOf(0); + /** Reusable Integer constant for one. */ + public static final Integer INTEGER_ONE = Integer.valueOf(1); + /** Reusable Integer constant for minus one. */ + public static final Integer INTEGER_MINUS_ONE = Integer.valueOf(-1); + /** Reusable Short constant for zero. */ + public static final Short SHORT_ZERO = Short.valueOf((short) 0); + /** Reusable Short constant for one. */ + public static final Short SHORT_ONE = Short.valueOf((short) 1); + /** Reusable Short constant for minus one. */ + public static final Short SHORT_MINUS_ONE = Short.valueOf((short) -1); + /** Reusable Byte constant for zero. */ + public static final Byte BYTE_ZERO = Byte.valueOf((byte) 0); + /** Reusable Byte constant for one. */ + public static final Byte BYTE_ONE = Byte.valueOf((byte) 1); + /** Reusable Byte constant for minus one. */ + public static final Byte BYTE_MINUS_ONE = Byte.valueOf((byte) -1); + /** Reusable Double constant for zero. */ + public static final Double DOUBLE_ZERO = Double.valueOf(0.0d); + /** Reusable Double constant for one. */ + public static final Double DOUBLE_ONE = Double.valueOf(1.0d); + /** Reusable Double constant for minus one. */ + public static final Double DOUBLE_MINUS_ONE = Double.valueOf(-1.0d); + /** Reusable Float constant for zero. */ + public static final Float FLOAT_ZERO = Float.valueOf(0.0f); + /** Reusable Float constant for one. */ + public static final Float FLOAT_ONE = Float.valueOf(1.0f); + /** Reusable Float constant for minus one. */ + public static final Float FLOAT_MINUS_ONE = Float.valueOf(-1.0f); + + /** + *

NumberUtils instances should NOT be constructed in standard programming. + * Instead, the class should be used as NumberUtils.toInt("6");.

+ * + *

This constructor is public to permit tools that require a JavaBean instance + * to operate.

+ */ + public NumberUtils() { + super(); + } + + //----------------------------------------------------------------------- + /** + *

Convert a String to an int, returning + * zero if the conversion fails.

+ * + *

If the string is null, zero is returned.

+ * + *
+     *   NumberUtils.toInt(null) = 0
+     *   NumberUtils.toInt("")   = 0
+     *   NumberUtils.toInt("1")  = 1
+     * 
+ * + * @param str the string to convert, may be null + * @return the int represented by the string, or zero if + * conversion fails + * @since 2.1 + */ + public static int toInt(final String str) { + return toInt(str, 0); + } + + /** + *

Convert a String to an int, returning a + * default value if the conversion fails.

+ * + *

If the string is null, the default value is returned.

+ * + *
+     *   NumberUtils.toInt(null, 1) = 1
+     *   NumberUtils.toInt("", 1)   = 1
+     *   NumberUtils.toInt("1", 0)  = 1
+     * 
+ * + * @param str the string to convert, may be null + * @param defaultValue the default value + * @return the int represented by the string, or the default if conversion fails + * @since 2.1 + */ + public static int toInt(final String str, final int defaultValue) { + if(str == null) { + return defaultValue; + } + try { + return Integer.parseInt(str); + } catch (final NumberFormatException nfe) { + return defaultValue; + } + } + + /** + *

Convert a String to a long, returning + * zero if the conversion fails.

+ * + *

If the string is null, zero is returned.

+ * + *
+     *   NumberUtils.toLong(null) = 0L
+     *   NumberUtils.toLong("")   = 0L
+     *   NumberUtils.toLong("1")  = 1L
+     * 
+ * + * @param str the string to convert, may be null + * @return the long represented by the string, or 0 if + * conversion fails + * @since 2.1 + */ + public static long toLong(final String str) { + return toLong(str, 0L); + } + + /** + *

Convert a String to a long, returning a + * default value if the conversion fails.

+ * + *

If the string is null, the default value is returned.

+ * + *
+     *   NumberUtils.toLong(null, 1L) = 1L
+     *   NumberUtils.toLong("", 1L)   = 1L
+     *   NumberUtils.toLong("1", 0L)  = 1L
+     * 
+ * + * @param str the string to convert, may be null + * @param defaultValue the default value + * @return the long represented by the string, or the default if conversion fails + * @since 2.1 + */ + public static long toLong(final String str, final long defaultValue) { + if (str == null) { + return defaultValue; + } + try { + return Long.parseLong(str); + } catch (final NumberFormatException nfe) { + return defaultValue; + } + } + + /** + *

Convert a String to a float, returning + * 0.0f if the conversion fails.

+ * + *

If the string str is null, + * 0.0f is returned.

+ * + *
+     *   NumberUtils.toFloat(null)   = 0.0f
+     *   NumberUtils.toFloat("")     = 0.0f
+     *   NumberUtils.toFloat("1.5")  = 1.5f
+     * 
+ * + * @param str the string to convert, may be null + * @return the float represented by the string, or 0.0f + * if conversion fails + * @since 2.1 + */ + public static float toFloat(final String str) { + return toFloat(str, 0.0f); + } + + /** + *

Convert a String to a float, returning a + * default value if the conversion fails.

+ * + *

If the string str is null, the default + * value is returned.

+ * + *
+     *   NumberUtils.toFloat(null, 1.1f)   = 1.0f
+     *   NumberUtils.toFloat("", 1.1f)     = 1.1f
+     *   NumberUtils.toFloat("1.5", 0.0f)  = 1.5f
+     * 
+ * + * @param str the string to convert, may be null + * @param defaultValue the default value + * @return the float represented by the string, or defaultValue + * if conversion fails + * @since 2.1 + */ + public static float toFloat(final String str, final float defaultValue) { + if (str == null) { + return defaultValue; + } + try { + return Float.parseFloat(str); + } catch (final NumberFormatException nfe) { + return defaultValue; + } + } + + /** + *

Convert a String to a double, returning + * 0.0d if the conversion fails.

+ * + *

If the string str is null, + * 0.0d is returned.

+ * + *
+     *   NumberUtils.toDouble(null)   = 0.0d
+     *   NumberUtils.toDouble("")     = 0.0d
+     *   NumberUtils.toDouble("1.5")  = 1.5d
+     * 
+ * + * @param str the string to convert, may be null + * @return the double represented by the string, or 0.0d + * if conversion fails + * @since 2.1 + */ + public static double toDouble(final String str) { + return toDouble(str, 0.0d); + } + + /** + *

Convert a String to a double, returning a + * default value if the conversion fails.

+ * + *

If the string str is null, the default + * value is returned.

+ * + *
+     *   NumberUtils.toDouble(null, 1.1d)   = 1.1d
+     *   NumberUtils.toDouble("", 1.1d)     = 1.1d
+     *   NumberUtils.toDouble("1.5", 0.0d)  = 1.5d
+     * 
+ * + * @param str the string to convert, may be null + * @param defaultValue the default value + * @return the double represented by the string, or defaultValue + * if conversion fails + * @since 2.1 + */ + public static double toDouble(final String str, final double defaultValue) { + if (str == null) { + return defaultValue; + } + try { + return Double.parseDouble(str); + } catch (final NumberFormatException nfe) { + return defaultValue; + } + } + + //----------------------------------------------------------------------- + /** + *

Convert a String to a byte, returning + * zero if the conversion fails.

+ * + *

If the string is null, zero is returned.

+ * + *
+     *   NumberUtils.toByte(null) = 0
+     *   NumberUtils.toByte("")   = 0
+     *   NumberUtils.toByte("1")  = 1
+     * 
+ * + * @param str the string to convert, may be null + * @return the byte represented by the string, or zero if + * conversion fails + * @since 2.5 + */ + public static byte toByte(final String str) { + return toByte(str, (byte) 0); + } + + /** + *

Convert a String to a byte, returning a + * default value if the conversion fails.

+ * + *

If the string is null, the default value is returned.

+ * + *
+     *   NumberUtils.toByte(null, 1) = 1
+     *   NumberUtils.toByte("", 1)   = 1
+     *   NumberUtils.toByte("1", 0)  = 1
+     * 
+ * + * @param str the string to convert, may be null + * @param defaultValue the default value + * @return the byte represented by the string, or the default if conversion fails + * @since 2.5 + */ + public static byte toByte(final String str, final byte defaultValue) { + if(str == null) { + return defaultValue; + } + try { + return Byte.parseByte(str); + } catch (final NumberFormatException nfe) { + return defaultValue; + } + } + + /** + *

Convert a String to a short, returning + * zero if the conversion fails.

+ * + *

If the string is null, zero is returned.

+ * + *
+     *   NumberUtils.toShort(null) = 0
+     *   NumberUtils.toShort("")   = 0
+     *   NumberUtils.toShort("1")  = 1
+     * 
+ * + * @param str the string to convert, may be null + * @return the short represented by the string, or zero if + * conversion fails + * @since 2.5 + */ + public static short toShort(final String str) { + return toShort(str, (short) 0); + } + + /** + *

Convert a String to an short, returning a + * default value if the conversion fails.

+ * + *

If the string is null, the default value is returned.

+ * + *
+     *   NumberUtils.toShort(null, 1) = 1
+     *   NumberUtils.toShort("", 1)   = 1
+     *   NumberUtils.toShort("1", 0)  = 1
+     * 
+ * + * @param str the string to convert, may be null + * @param defaultValue the default value + * @return the short represented by the string, or the default if conversion fails + * @since 2.5 + */ + public static short toShort(final String str, final short defaultValue) { + if(str == null) { + return defaultValue; + } + try { + return Short.parseShort(str); + } catch (final NumberFormatException nfe) { + return defaultValue; + } + } + + //----------------------------------------------------------------------- + // must handle Long, Float, Integer, Float, Short, + // BigDecimal, BigInteger and Byte + // useful methods: + // Byte.decode(String) + // Byte.valueOf(String,int radix) + // Byte.valueOf(String) + // Double.valueOf(String) + // Float.valueOf(String) + // Float.valueOf(String) + // Integer.valueOf(String,int radix) + // Integer.valueOf(String) + // Integer.decode(String) + // Integer.getInteger(String) + // Integer.getInteger(String,int val) + // Integer.getInteger(String,Integer val) + // Integer.valueOf(String) + // Double.valueOf(String) + // new Byte(String) + // Long.valueOf(String) + // Long.getLong(String) + // Long.getLong(String,int) + // Long.getLong(String,Integer) + // Long.valueOf(String,int) + // Long.valueOf(String) + // Short.valueOf(String) + // Short.decode(String) + // Short.valueOf(String,int) + // Short.valueOf(String) + // new BigDecimal(String) + // new BigInteger(String) + // new BigInteger(String,int radix) + // Possible inputs: + // 45 45.5 45E7 4.5E7 Hex Oct Binary xxxF xxxD xxxf xxxd + // plus minus everything. Prolly more. A lot are not separable. + + /** + *

Turns a string value into a java.lang.Number.

+ * + *

If the string starts with {@code 0x} or {@code -0x} (lower or upper case) or {@code #} or {@code -#}, it + * will be interpreted as a hexadecimal Integer - or Long, if the number of digits after the + * prefix is more than 8 - or BigInteger if there are more than 16 digits. + *

+ *

Then, the value is examined for a type qualifier on the end, i.e. one of + * 'f','F','d','D','l','L'. If it is found, it starts + * trying to create successively larger types from the type specified + * until one is found that can represent the value.

+ * + *

If a type specifier is not found, it will check for a decimal point + * and then try successively larger types from Integer to + * BigInteger and from Float to + * BigDecimal.

+ * + *

+ * Integral values with a leading {@code 0} will be interpreted as octal; the returned number will + * be Integer, Long or BigDecimal as appropriate. + *

+ * + *

Returns null if the string is null.

+ * + *

This method does not trim the input string, i.e., strings with leading + * or trailing spaces will generate NumberFormatExceptions.

+ * + * @param str String containing a number, may be null + * @return Number created from the string (or null if the input is null) + * @throws NumberFormatException if the value cannot be converted + */ + public static Number createNumber(final String str) throws NumberFormatException { + if (str == null) { + return null; + } + if (StringUtils.isBlank(str)) { + throw new NumberFormatException("A blank string is not a valid number"); + } + // Need to deal with all possible hex prefixes here + final String[] hex_prefixes = {"0x", "0X", "-0x", "-0X", "#", "-#"}; + int pfxLen = 0; + for(final String pfx : hex_prefixes) { + if (str.startsWith(pfx)) { + pfxLen += pfx.length(); + break; + } + } + if (pfxLen > 0) { // we have a hex number + char firstSigDigit = 0; // strip leading zeroes + for(int i = pfxLen; i < str.length(); i++) { + firstSigDigit = str.charAt(i); + if (firstSigDigit == '0') { // count leading zeroes + pfxLen++; + } else { + break; + } + } + final int hexDigits = str.length() - pfxLen; + if (hexDigits > 16 || hexDigits == 16 && firstSigDigit > '7') { // too many for Long + return createBigInteger(str); + } + if (hexDigits > 8 || hexDigits == 8 && firstSigDigit > '7') { // too many for an int + return createLong(str); + } + return createInteger(str); + } + final char lastChar = str.charAt(str.length() - 1); + String mant; + String dec; + String exp; + final int decPos = str.indexOf('.'); + final int expPos = str.indexOf('e') + str.indexOf('E') + 1; // assumes both not present + // if both e and E are present, this is caught by the checks on expPos (which prevent IOOBE) + // and the parsing which will detect if e or E appear in a number due to using the wrong offset + + if (decPos > -1) { // there is a decimal point + if (expPos > -1) { // there is an exponent + if (expPos < decPos || expPos > str.length()) { // prevents double exponent causing IOOBE + throw new NumberFormatException(str + " is not a valid number."); + } + dec = str.substring(decPos + 1, expPos); + } else { + dec = str.substring(decPos + 1); + } + mant = getMantissa(str, decPos); + } else { + if (expPos > -1) { + if (expPos > str.length()) { // prevents double exponent causing IOOBE + throw new NumberFormatException(str + " is not a valid number."); + } + mant = getMantissa(str, expPos); + } else { + mant = getMantissa(str); + } + dec = null; + } + if (!Character.isDigit(lastChar) && lastChar != '.') { + if (expPos > -1 && expPos < str.length() - 1) { + exp = str.substring(expPos + 1, str.length() - 1); + } else { + exp = null; + } + //Requesting a specific type.. + final String numeric = str.substring(0, str.length() - 1); + final boolean allZeros = isAllZeros(mant) && isAllZeros(exp); + switch (lastChar) { + case 'l' : + case 'L' : + if (dec == null + && exp == null + && (numeric.charAt(0) == '-' && isDigits(numeric.substring(1)) || isDigits(numeric))) { + try { + return createLong(numeric); + } catch (final NumberFormatException nfe) { // NOPMD + // Too big for a long + } + return createBigInteger(numeric); + + } + throw new NumberFormatException(str + " is not a valid number."); + case 'f' : + case 'F' : + try { + final Float f = NumberUtils.createFloat(str); + if (!(f.isInfinite() || f.floatValue() == 0.0F && !allZeros)) { + //If it's too big for a float or the float value = 0 and the string + //has non-zeros in it, then float does not have the precision we want + return f; + } + + } catch (final NumberFormatException nfe) { // NOPMD + // ignore the bad number + } + //$FALL-THROUGH$ + case 'd' : + case 'D' : + try { + final Double d = NumberUtils.createDouble(str); + if (!(d.isInfinite() || d.floatValue() == 0.0D && !allZeros)) { + return d; + } + } catch (final NumberFormatException nfe) { // NOPMD + // ignore the bad number + } + try { + return createBigDecimal(numeric); + } catch (final NumberFormatException e) { // NOPMD + // ignore the bad number + } + //$FALL-THROUGH$ + default : + throw new NumberFormatException(str + " is not a valid number."); + + } + } + //User doesn't have a preference on the return type, so let's start + //small and go from there... + if (expPos > -1 && expPos < str.length() - 1) { + exp = str.substring(expPos + 1, str.length()); + } else { + exp = null; + } + if (dec == null && exp == null) { // no decimal point and no exponent + //Must be an Integer, Long, Biginteger + try { + return createInteger(str); + } catch (final NumberFormatException nfe) { // NOPMD + // ignore the bad number + } + try { + return createLong(str); + } catch (final NumberFormatException nfe) { // NOPMD + // ignore the bad number + } + return createBigInteger(str); + } + + //Must be a Float, Double, BigDecimal + final boolean allZeros = isAllZeros(mant) && isAllZeros(exp); + try { + final Float f = createFloat(str); + final Double d = createDouble(str); + if (!f.isInfinite() + && !(f.floatValue() == 0.0F && !allZeros) + && f.toString().equals(d.toString())) { + return f; + } + if (!d.isInfinite() && !(d.doubleValue() == 0.0D && !allZeros)) { + final BigDecimal b = createBigDecimal(str); + if (b.compareTo(BigDecimal.valueOf(d)) == 0) { + return d; + } + return b; + } + } catch (final NumberFormatException nfe) { // NOPMD + // ignore the bad number + } + return createBigDecimal(str); + } + + /** + *

Utility method for {@link #createNumber(java.lang.String)}.

+ * + *

Returns mantissa of the given number.

+ * + * @param str the string representation of the number + * @return mantissa of the given number + */ + private static String getMantissa(final String str) { + return getMantissa(str, str.length()); + } + + /** + *

Utility method for {@link #createNumber(java.lang.String)}.

+ * + *

Returns mantissa of the given number.

+ * + * @param str the string representation of the number + * @param stopPos the position of the exponent or decimal point + * @return mantissa of the given number + */ + private static String getMantissa(final String str, final int stopPos) { + final char firstChar = str.charAt(0); + final boolean hasSign = firstChar == '-' || firstChar == '+'; + + return hasSign ? str.substring(1, stopPos) : str.substring(0, stopPos); + } + + /** + *

Utility method for {@link #createNumber(java.lang.String)}.

+ * + *

Returns true if s is null.

+ * + * @param str the String to check + * @return if it is all zeros or null + */ + private static boolean isAllZeros(final String str) { + if (str == null) { + return true; + } + for (int i = str.length() - 1; i >= 0; i--) { + if (str.charAt(i) != '0') { + return false; + } + } + return str.length() > 0; + } + + //----------------------------------------------------------------------- + /** + *

Convert a String to a Float.

+ * + *

Returns null if the string is null.

+ * + * @param str a String to convert, may be null + * @return converted Float (or null if the input is null) + * @throws NumberFormatException if the value cannot be converted + */ + public static Float createFloat(final String str) { + if (str == null) { + return null; + } + return Float.valueOf(str); + } + + /** + *

Convert a String to a Double.

+ * + *

Returns null if the string is null.

+ * + * @param str a String to convert, may be null + * @return converted Double (or null if the input is null) + * @throws NumberFormatException if the value cannot be converted + */ + public static Double createDouble(final String str) { + if (str == null) { + return null; + } + return Double.valueOf(str); + } + + /** + *

Convert a String to a Integer, handling + * hex (0xhhhh) and octal (0dddd) notations. + * N.B. a leading zero means octal; spaces are not trimmed.

+ * + *

Returns null if the string is null.

+ * + * @param str a String to convert, may be null + * @return converted Integer (or null if the input is null) + * @throws NumberFormatException if the value cannot be converted + */ + public static Integer createInteger(final String str) { + if (str == null) { + return null; + } + // decode() handles 0xAABD and 0777 (hex and octal) as well. + return Integer.decode(str); + } + + /** + *

Convert a String to a Long; + * since 3.1 it handles hex (0Xhhhh) and octal (0ddd) notations. + * N.B. a leading zero means octal; spaces are not trimmed.

+ * + *

Returns null if the string is null.

+ * + * @param str a String to convert, may be null + * @return converted Long (or null if the input is null) + * @throws NumberFormatException if the value cannot be converted + */ + public static Long createLong(final String str) { + if (str == null) { + return null; + } + return Long.decode(str); + } + + /** + *

Convert a String to a BigInteger; + * since 3.2 it handles hex (0x or #) and octal (0) notations.

+ * + *

Returns null if the string is null.

+ * + * @param str a String to convert, may be null + * @return converted BigInteger (or null if the input is null) + * @throws NumberFormatException if the value cannot be converted + */ +/** + *

Convert a String to a BigInteger; + * since 3.2 it handles hex (0x or #) and octal (0) notations.

+ * + *

Returns null if the string is null.

+ * + * @param str + * a String to convert, may be null + * @return converted BigInteger (or null if the input is null) + * @throws NumberFormatException + * if the value cannot be converted + */ +public static java.math.BigInteger createBigInteger(final java.lang.String str) { + { + int pos = 0;// offset within string + + int radix = 10; + boolean negate = false;// need to negate later? + + if (/* NPEX_NULL_EXP */ + str.startsWith("-")) { + negate = true; + pos = 1; + } + if (str.startsWith("0x", pos) || str.startsWith("0X", pos)) { + // hex + radix = 16; + pos += 2; + }// default is to treat as decimal + else if (str.startsWith("#", pos)) { + // alternative hex (allowed by Long/Integer) + radix = 16; + pos++; + } else if (str.startsWith("0", pos) && (str.length() > (pos + 1))) { + // octal; so long as there are additional digits + radix = 8; + pos++; + }// default is to treat as decimal + + final java.math.BigInteger value = new java.math.BigInteger(str.substring(pos), radix); + return negate ? value.negate() : value; + } +} + + /** + *

Convert a String to a BigDecimal.

+ * + *

Returns null if the string is null.

+ * + * @param str a String to convert, may be null + * @return converted BigDecimal (or null if the input is null) + * @throws NumberFormatException if the value cannot be converted + */ + public static BigDecimal createBigDecimal(final String str) { + if (str == null) { + return null; + } + // handle JDK1.3.1 bug where "" throws IndexOutOfBoundsException + if (StringUtils.isBlank(str)) { + throw new NumberFormatException("A blank string is not a valid number"); + } + if (str.trim().startsWith("--")) { + // this is protection for poorness in java.lang.BigDecimal. + // it accepts this as a legal value, but it does not appear + // to be in specification of class. OS X Java parses it to + // a wrong value. + throw new NumberFormatException(str + " is not a valid number."); + } + return new BigDecimal(str); + } + + // Min in array + //-------------------------------------------------------------------- + /** + *

Returns the minimum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the minimum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @since 3.4 Changed signature from min(long[]) to min(long...) + */ + public static long min(final long... array) { + // Validates input + validateArray(array); + + // Finds and returns min + long min = array[0]; + for (int i = 1; i < array.length; i++) { + if (array[i] < min) { + min = array[i]; + } + } + + return min; + } + + /** + *

Returns the minimum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the minimum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @since 3.4 Changed signature from min(int[]) to min(int...) + */ + public static int min(final int... array) { + // Validates input + validateArray(array); + + // Finds and returns min + int min = array[0]; + for (int j = 1; j < array.length; j++) { + if (array[j] < min) { + min = array[j]; + } + } + + return min; + } + + /** + *

Returns the minimum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the minimum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @since 3.4 Changed signature from min(short[]) to min(short...) + */ + public static short min(final short... array) { + // Validates input + validateArray(array); + + // Finds and returns min + short min = array[0]; + for (int i = 1; i < array.length; i++) { + if (array[i] < min) { + min = array[i]; + } + } + + return min; + } + + /** + *

Returns the minimum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the minimum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @since 3.4 Changed signature from min(byte[]) to min(byte...) + */ + public static byte min(final byte... array) { + // Validates input + validateArray(array); + + // Finds and returns min + byte min = array[0]; + for (int i = 1; i < array.length; i++) { + if (array[i] < min) { + min = array[i]; + } + } + + return min; + } + + /** + *

Returns the minimum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the minimum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @see IEEE754rUtils#min(double[]) IEEE754rUtils for a version of this method that handles NaN differently + * @since 3.4 Changed signature from min(double[]) to min(double...) + */ + public static double min(final double... array) { + // Validates input + validateArray(array); + + // Finds and returns min + double min = array[0]; + for (int i = 1; i < array.length; i++) { + if (Double.isNaN(array[i])) { + return Double.NaN; + } + if (array[i] < min) { + min = array[i]; + } + } + + return min; + } + + /** + *

Returns the minimum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the minimum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @see IEEE754rUtils#min(float[]) IEEE754rUtils for a version of this method that handles NaN differently + * @since 3.4 Changed signature from min(float[]) to min(float...) + */ + public static float min(final float... array) { + // Validates input + validateArray(array); + + // Finds and returns min + float min = array[0]; + for (int i = 1; i < array.length; i++) { + if (Float.isNaN(array[i])) { + return Float.NaN; + } + if (array[i] < min) { + min = array[i]; + } + } + + return min; + } + + // Max in array + //-------------------------------------------------------------------- + /** + *

Returns the maximum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the maximum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @since 3.4 Changed signature from max(long[]) to max(long...) + */ + public static long max(final long... array) { + // Validates input + validateArray(array); + + // Finds and returns max + long max = array[0]; + for (int j = 1; j < array.length; j++) { + if (array[j] > max) { + max = array[j]; + } + } + + return max; + } + + /** + *

Returns the maximum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the maximum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @since 3.4 Changed signature from max(int[]) to max(int...) + */ + public static int max(final int... array) { + // Validates input + validateArray(array); + + // Finds and returns max + int max = array[0]; + for (int j = 1; j < array.length; j++) { + if (array[j] > max) { + max = array[j]; + } + } + + return max; + } + + /** + *

Returns the maximum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the maximum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @since 3.4 Changed signature from max(short[]) to max(short...) + */ + public static short max(final short... array) { + // Validates input + validateArray(array); + + // Finds and returns max + short max = array[0]; + for (int i = 1; i < array.length; i++) { + if (array[i] > max) { + max = array[i]; + } + } + + return max; + } + + /** + *

Returns the maximum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the maximum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @since 3.4 Changed signature from max(byte[]) to max(byte...) + */ + public static byte max(final byte... array) { + // Validates input + validateArray(array); + + // Finds and returns max + byte max = array[0]; + for (int i = 1; i < array.length; i++) { + if (array[i] > max) { + max = array[i]; + } + } + + return max; + } + + /** + *

Returns the maximum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the maximum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @see IEEE754rUtils#max(double[]) IEEE754rUtils for a version of this method that handles NaN differently + * @since 3.4 Changed signature from max(double[]) to max(double...) + */ + public static double max(final double... array) { + // Validates input + validateArray(array); + + // Finds and returns max + double max = array[0]; + for (int j = 1; j < array.length; j++) { + if (Double.isNaN(array[j])) { + return Double.NaN; + } + if (array[j] > max) { + max = array[j]; + } + } + + return max; + } + + /** + *

Returns the maximum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the maximum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @see IEEE754rUtils#max(float[]) IEEE754rUtils for a version of this method that handles NaN differently + * @since 3.4 Changed signature from max(float[]) to max(float...) + */ + public static float max(final float... array) { + // Validates input + validateArray(array); + + // Finds and returns max + float max = array[0]; + for (int j = 1; j < array.length; j++) { + if (Float.isNaN(array[j])) { + return Float.NaN; + } + if (array[j] > max) { + max = array[j]; + } + } + + return max; + } + + /** + * Checks if the specified array is neither null nor empty. + * + * @param array the array to check + * @throws IllegalArgumentException if {@code array} is either {@code null} or empty + */ + private static void validateArray(final Object array) { + if (array == null) { + throw new IllegalArgumentException("The Array must not be null"); + } + Validate.isTrue(Array.getLength(array) != 0, "Array cannot be empty."); + } + + // 3 param min + //----------------------------------------------------------------------- + /** + *

Gets the minimum of three long values.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the smallest of the values + */ + public static long min(long a, final long b, final long c) { + if (b < a) { + a = b; + } + if (c < a) { + a = c; + } + return a; + } + + /** + *

Gets the minimum of three int values.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the smallest of the values + */ + public static int min(int a, final int b, final int c) { + if (b < a) { + a = b; + } + if (c < a) { + a = c; + } + return a; + } + + /** + *

Gets the minimum of three short values.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the smallest of the values + */ + public static short min(short a, final short b, final short c) { + if (b < a) { + a = b; + } + if (c < a) { + a = c; + } + return a; + } + + /** + *

Gets the minimum of three byte values.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the smallest of the values + */ + public static byte min(byte a, final byte b, final byte c) { + if (b < a) { + a = b; + } + if (c < a) { + a = c; + } + return a; + } + + /** + *

Gets the minimum of three double values.

+ * + *

If any value is NaN, NaN is + * returned. Infinity is handled.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the smallest of the values + * @see IEEE754rUtils#min(double, double, double) for a version of this method that handles NaN differently + */ + public static double min(final double a, final double b, final double c) { + return Math.min(Math.min(a, b), c); + } + + /** + *

Gets the minimum of three float values.

+ * + *

If any value is NaN, NaN is + * returned. Infinity is handled.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the smallest of the values + * @see IEEE754rUtils#min(float, float, float) for a version of this method that handles NaN differently + */ + public static float min(final float a, final float b, final float c) { + return Math.min(Math.min(a, b), c); + } + + // 3 param max + //----------------------------------------------------------------------- + /** + *

Gets the maximum of three long values.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the largest of the values + */ + public static long max(long a, final long b, final long c) { + if (b > a) { + a = b; + } + if (c > a) { + a = c; + } + return a; + } + + /** + *

Gets the maximum of three int values.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the largest of the values + */ + public static int max(int a, final int b, final int c) { + if (b > a) { + a = b; + } + if (c > a) { + a = c; + } + return a; + } + + /** + *

Gets the maximum of three short values.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the largest of the values + */ + public static short max(short a, final short b, final short c) { + if (b > a) { + a = b; + } + if (c > a) { + a = c; + } + return a; + } + + /** + *

Gets the maximum of three byte values.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the largest of the values + */ + public static byte max(byte a, final byte b, final byte c) { + if (b > a) { + a = b; + } + if (c > a) { + a = c; + } + return a; + } + + /** + *

Gets the maximum of three double values.

+ * + *

If any value is NaN, NaN is + * returned. Infinity is handled.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the largest of the values + * @see IEEE754rUtils#max(double, double, double) for a version of this method that handles NaN differently + */ + public static double max(final double a, final double b, final double c) { + return Math.max(Math.max(a, b), c); + } + + /** + *

Gets the maximum of three float values.

+ * + *

If any value is NaN, NaN is + * returned. Infinity is handled.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the largest of the values + * @see IEEE754rUtils#max(float, float, float) for a version of this method that handles NaN differently + */ + public static float max(final float a, final float b, final float c) { + return Math.max(Math.max(a, b), c); + } + + //----------------------------------------------------------------------- + /** + *

Checks whether the String contains only + * digit characters.

+ * + *

Null and empty String will return + * false.

+ * + * @param str the String to check + * @return true if str contains only Unicode numeric + */ + public static boolean isDigits(final String str) { + return StringUtils.isNumeric(str); + } + + /** + *

Checks whether the String a valid Java number.

+ * + *

Valid numbers include hexadecimal marked with the 0x or + * 0X qualifier, octal numbers, scientific notation and + * numbers marked with a type qualifier (e.g. 123L).

+ * + *

Non-hexadecimal strings beginning with a leading zero are + * treated as octal values. Thus the string 09 will return + * false, since 9 is not a valid octal value. + * However, numbers beginning with {@code 0.} are treated as decimal.

+ * + *

null and empty/blank {@code String} will return + * false.

+ * + *

Note, {@link #createNumber(String)} should return a number for every + * input resuling in true.

+ * + * @param str the String to check + * @return true if the string is a correctly formatted number + * @since 3.3 the code supports hex {@code 0Xhhh} an + * octal {@code 0ddd} validation + * @deprecated This feature will be removed in Lang 4.0, + * use {@link NumberUtils#isCreatable(String)} instead + */ + @Deprecated + public static boolean isNumber(final String str) { + return isCreatable(str); + } + + /** + *

Checks whether the String a valid Java number.

+ * + *

Valid numbers include hexadecimal marked with the 0x or + * 0X qualifier, octal numbers, scientific notation and + * numbers marked with a type qualifier (e.g. 123L).

+ * + *

Non-hexadecimal strings beginning with a leading zero are + * treated as octal values. Thus the string 09 will return + * false, since 9 is not a valid octal value. + * However, numbers beginning with {@code 0.} are treated as decimal.

+ * + *

null and empty/blank {@code String} will return + * false.

+ * + *

Note, {@link #createNumber(String)} should return a number for every + * input resuling in true.

+ * + * @param str the String to check + * @return true if the string is a correctly formatted number + * @since 3.5 the code supports the "+" suffix on numbers except for integers in Java 1.6 + */ + public static boolean isCreatable(final String str) { + if (StringUtils.isEmpty(str)) { + return false; + } + final char[] chars = str.toCharArray(); + int sz = chars.length; + boolean hasExp = false; + boolean hasDecPoint = false; + boolean allowSigns = false; + boolean foundDigit = false; + // deal with any possible sign up front + final int start = chars[0] == '-' || chars[0] == '+' ? 1 : 0; + final boolean hasLeadingPlusSign = start == 1 && chars[0] == '+'; + if (sz > start + 1 && chars[start] == '0') { // leading 0 + if (chars[start + 1] == 'x' || chars[start + 1] == 'X') { // leading 0x/0X + int i = start + 2; + if (i == sz) { + return false; // str == "0x" + } + // checking hex (it can't be anything else) + for (; i < chars.length; i++) { + if ((chars[i] < '0' || chars[i] > '9') + && (chars[i] < 'a' || chars[i] > 'f') + && (chars[i] < 'A' || chars[i] > 'F')) { + return false; + } + } + return true; + } else if (Character.isDigit(chars[start + 1])) { + // leading 0, but not hex, must be octal + int i = start + 1; + for (; i < chars.length; i++) { + if (chars[i] < '0' || chars[i] > '7') { + return false; + } + } + return true; + } + } + sz--; // don't want to loop to the last char, check it afterwords + // for type qualifiers + int i = start; + // loop to the next to last char or to the last char if we need another digit to + // make a valid number (e.g. chars[0..5] = "1234E") + while (i < sz || i < sz + 1 && allowSigns && !foundDigit) { + if (chars[i] >= '0' && chars[i] <= '9') { + foundDigit = true; + allowSigns = false; + + } else if (chars[i] == '.') { + if (hasDecPoint || hasExp) { + // two decimal points or dec in exponent + return false; + } + hasDecPoint = true; + } else if (chars[i] == 'e' || chars[i] == 'E') { + // we've already taken care of hex. + if (hasExp) { + // two E's + return false; + } + if (!foundDigit) { + return false; + } + hasExp = true; + allowSigns = true; + } else if (chars[i] == '+' || chars[i] == '-') { + if (!allowSigns) { + return false; + } + allowSigns = false; + foundDigit = false; // we need a digit after the E + } else { + return false; + } + i++; + } + if (i < chars.length) { + if (chars[i] >= '0' && chars[i] <= '9') { + if (SystemUtils.IS_JAVA_1_6 && hasLeadingPlusSign && !hasDecPoint) { + return false; + } + // no type qualifier, OK + return true; + } + if (chars[i] == 'e' || chars[i] == 'E') { + // can't have an E at the last byte + return false; + } + if (chars[i] == '.') { + if (hasDecPoint || hasExp) { + // two decimal points or dec in exponent + return false; + } + // single trailing decimal point after non-exponent is ok + return foundDigit; + } + if (!allowSigns + && (chars[i] == 'd' + || chars[i] == 'D' + || chars[i] == 'f' + || chars[i] == 'F')) { + return foundDigit; + } + if (chars[i] == 'l' + || chars[i] == 'L') { + // not allowing L with an exponent or decimal point + return foundDigit && !hasExp && !hasDecPoint; + } + // last character is illegal + return false; + } + // allowSigns is true iff the val ends in 'E' + // found digit it to make sure weird stuff like '.' and '1E-' doesn't pass + return !allowSigns && foundDigit; + } + + /** + *

Checks whether the given String is a parsable number.

+ * + *

Parsable numbers include those Strings understood by {@link Integer#parseInt(String)}, + * {@link Long#parseLong(String)}, {@link Float#parseFloat(String)} or + * {@link Double#parseDouble(String)}. This method can be used instead of catching {@link java.text.ParseException} + * when calling one of those methods.

+ * + *

Hexadecimal and scientific notations are not considered parsable. + * See {@link #isCreatable(String)} on those cases.

+ * + *

{@code Null} and empty String will return false.

+ * + * @param str the String to check. + * @return {@code true} if the string is a parsable number. + * @since 3.4 + */ + public static boolean isParsable(final String str) { + if (StringUtils.isEmpty(str)) { + return false; + } + if (str.charAt(str.length() - 1) == '.') { + return false; + } + if (str.charAt(0) == '-') { + if (str.length() == 1) { + return false; + } + return withDecimalsParsing(str, 1); + } else { + return withDecimalsParsing(str, 0); + } + } + + private static boolean withDecimalsParsing(final String str, final int beginIdx) { + int decimalPoints = 0; + for (int i = beginIdx; i < str.length(); i++) { + final boolean isDecimalPoint = str.charAt(i) == '.'; + if (isDecimalPoint) { + decimalPoints++; + } + if (decimalPoints > 1) { + return false; + } + if (!isDecimalPoint && !Character.isDigit(str.charAt(i))) { + return false; + } + } + return true; + } + + /** + *

Compares two {@code int} values numerically. This is the same functionality as provided in Java 7.

+ * + * @param x the first {@code int} to compare + * @param y the second {@code int} 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(int x, int y) { + if (x == y) { + return 0; + } + return x < y ? -1 : 1; + } + + /** + *

Compares to {@code long} values numerically. This is the same functionality as provided in Java 7.

+ * + * @param x the first {@code long} to compare + * @param y the second {@code long} 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(long x, long y) { + if (x == y) { + return 0; + } + return x < y ? -1 : 1; + } + + /** + *

Compares to {@code short} values numerically. This is the same functionality as provided in Java 7.

+ * + * @param x the first {@code short} to compare + * @param y the second {@code short} 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(short x, short y) { + if (x == y) { + return 0; + } + return x < y ? -1 : 1; + } + + /** + *

Compares two {@code byte} values numerically. This is the same functionality as provided in Java 7.

+ * + * @param x the first {@code byte} to compare + * @param y the second {@code byte} 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(byte x, byte y) { + return x - y; + } +} diff --git a/Java/commons-lang-NumberUtils_749/metadata.json b/Java/commons-lang-NumberUtils_749/metadata.json new file mode 100644 index 000000000..6437607d4 --- /dev/null +++ b/Java/commons-lang-NumberUtils_749/metadata.json @@ -0,0 +1,21 @@ +{ + "language": "java", + "id": "commons-lang-NumberUtils_749", + "buggyPath": ".", + "referencePath": null, + "buildCommand": "mvn package -V -B -Denforcer.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true -Drat.skip=true -Dlicense.skip=true -Dfindbugs.skip=true -Dgpg.skip=true -Dskip.npm=true -Dskip.gulp=true -Dskip.bower=true -Drat.numUnapprovedLicenses=100 -DskipTests=true -DskipITs=true -Dtest=None -DfailIfNoTests=false", + "testCommand": "mvn test -V -B -Denforcer.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true -Drat.skip=true -Dlicense.skip=true -Dfindbugs.skip=true -Dgpg.skip=true -Dskip.npm=true -Dskip.gulp=true -Dskip.bower=true -Drat.numUnapprovedLicenses=100", + "categories": [ + "safety", + "npe" + ], + "npe": { + "filepath": "src/main/java/org/apache/commons/lang3/math/NumberUtils.java", + "line": 768, + "npe_method": "createBigInteger", + "deref_field": "str", + "npe_class": "NumberUtils", + "repo": "commons-lang", + "bug_id": "NumberUtils_749" + } +} diff --git a/Java/commons-lang-NumberUtils_749/npe.json b/Java/commons-lang-NumberUtils_749/npe.json new file mode 100644 index 000000000..9ccb5adc2 --- /dev/null +++ b/Java/commons-lang-NumberUtils_749/npe.json @@ -0,0 +1,7 @@ +{ + "filepath": "src/main/java/org/apache/commons/lang3/math/NumberUtils.java", + "line": 768, + "npe_method": "createBigInteger", + "deref_field": "str", + "npe_class": "NumberUtils" +} \ No newline at end of file diff --git a/Java/commons-lang-NumberUtils_784/Dockerfile b/Java/commons-lang-NumberUtils_784/Dockerfile new file mode 100644 index 000000000..7b7fbe349 --- /dev/null +++ b/Java/commons-lang-NumberUtils_784/Dockerfile @@ -0,0 +1,18 @@ +FROM ghcr.io/kupl/starlab-benchmarks/java-base:commons-lang + +ENV TZ=Asia/Seoul + +COPY ./metadata.json . +COPY ./npe.json . +COPY ./buggy.java /tmp/buggy.java +RUN export BUGGY_PATH=$(cat metadata.json | jq -r ".npe.filepath") \ + && export BUGGY_LINE=$(cat metadata.json | jq -r ".npe.line") \ + && export BUGGY_MTHD=$(cat metadata.json | jq -r ".npe.npe_method") \ + && mv /tmp/buggy.java $BUGGY_PATH \ + && echo "[{\"filepath\": \"$BUGGY_PATH\", \"line\": $BUGGY_LINE, \"method_name\": \"$BUGGY_MTHD\"}]" | jq . > traces.json + +RUN git init . && git add -A + +RUN $(cat metadata.json | jq -r ".buildCommand") + +RUN $(cat metadata.json | jq -r ".testCommand"); if [ $? -eq 0 ]; then exit 1; fi diff --git a/Java/commons-lang-NumberUtils_784/buggy.java b/Java/commons-lang-NumberUtils_784/buggy.java new file mode 100644 index 000000000..43af83ddd --- /dev/null +++ b/Java/commons-lang-NumberUtils_784/buggy.java @@ -0,0 +1,1644 @@ +/* + * 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 java.lang.reflect.Array; +import java.math.BigDecimal; +import java.math.BigInteger; + +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.SystemUtils; +import org.apache.commons.lang3.Validate; + +/** + *

Provides extra functionality for Java Number classes.

+ * + * @since 2.0 + */ +public class NumberUtils { + + /** Reusable Long constant for zero. */ + public static final Long LONG_ZERO = Long.valueOf(0L); + /** Reusable Long constant for one. */ + public static final Long LONG_ONE = Long.valueOf(1L); + /** Reusable Long constant for minus one. */ + public static final Long LONG_MINUS_ONE = Long.valueOf(-1L); + /** Reusable Integer constant for zero. */ + public static final Integer INTEGER_ZERO = Integer.valueOf(0); + /** Reusable Integer constant for one. */ + public static final Integer INTEGER_ONE = Integer.valueOf(1); + /** Reusable Integer constant for minus one. */ + public static final Integer INTEGER_MINUS_ONE = Integer.valueOf(-1); + /** Reusable Short constant for zero. */ + public static final Short SHORT_ZERO = Short.valueOf((short) 0); + /** Reusable Short constant for one. */ + public static final Short SHORT_ONE = Short.valueOf((short) 1); + /** Reusable Short constant for minus one. */ + public static final Short SHORT_MINUS_ONE = Short.valueOf((short) -1); + /** Reusable Byte constant for zero. */ + public static final Byte BYTE_ZERO = Byte.valueOf((byte) 0); + /** Reusable Byte constant for one. */ + public static final Byte BYTE_ONE = Byte.valueOf((byte) 1); + /** Reusable Byte constant for minus one. */ + public static final Byte BYTE_MINUS_ONE = Byte.valueOf((byte) -1); + /** Reusable Double constant for zero. */ + public static final Double DOUBLE_ZERO = Double.valueOf(0.0d); + /** Reusable Double constant for one. */ + public static final Double DOUBLE_ONE = Double.valueOf(1.0d); + /** Reusable Double constant for minus one. */ + public static final Double DOUBLE_MINUS_ONE = Double.valueOf(-1.0d); + /** Reusable Float constant for zero. */ + public static final Float FLOAT_ZERO = Float.valueOf(0.0f); + /** Reusable Float constant for one. */ + public static final Float FLOAT_ONE = Float.valueOf(1.0f); + /** Reusable Float constant for minus one. */ + public static final Float FLOAT_MINUS_ONE = Float.valueOf(-1.0f); + + /** + *

NumberUtils instances should NOT be constructed in standard programming. + * Instead, the class should be used as NumberUtils.toInt("6");.

+ * + *

This constructor is public to permit tools that require a JavaBean instance + * to operate.

+ */ + public NumberUtils() { + super(); + } + + //----------------------------------------------------------------------- + /** + *

Convert a String to an int, returning + * zero if the conversion fails.

+ * + *

If the string is null, zero is returned.

+ * + *
+     *   NumberUtils.toInt(null) = 0
+     *   NumberUtils.toInt("")   = 0
+     *   NumberUtils.toInt("1")  = 1
+     * 
+ * + * @param str the string to convert, may be null + * @return the int represented by the string, or zero if + * conversion fails + * @since 2.1 + */ + public static int toInt(final String str) { + return toInt(str, 0); + } + + /** + *

Convert a String to an int, returning a + * default value if the conversion fails.

+ * + *

If the string is null, the default value is returned.

+ * + *
+     *   NumberUtils.toInt(null, 1) = 1
+     *   NumberUtils.toInt("", 1)   = 1
+     *   NumberUtils.toInt("1", 0)  = 1
+     * 
+ * + * @param str the string to convert, may be null + * @param defaultValue the default value + * @return the int represented by the string, or the default if conversion fails + * @since 2.1 + */ + public static int toInt(final String str, final int defaultValue) { + if(str == null) { + return defaultValue; + } + try { + return Integer.parseInt(str); + } catch (final NumberFormatException nfe) { + return defaultValue; + } + } + + /** + *

Convert a String to a long, returning + * zero if the conversion fails.

+ * + *

If the string is null, zero is returned.

+ * + *
+     *   NumberUtils.toLong(null) = 0L
+     *   NumberUtils.toLong("")   = 0L
+     *   NumberUtils.toLong("1")  = 1L
+     * 
+ * + * @param str the string to convert, may be null + * @return the long represented by the string, or 0 if + * conversion fails + * @since 2.1 + */ + public static long toLong(final String str) { + return toLong(str, 0L); + } + + /** + *

Convert a String to a long, returning a + * default value if the conversion fails.

+ * + *

If the string is null, the default value is returned.

+ * + *
+     *   NumberUtils.toLong(null, 1L) = 1L
+     *   NumberUtils.toLong("", 1L)   = 1L
+     *   NumberUtils.toLong("1", 0L)  = 1L
+     * 
+ * + * @param str the string to convert, may be null + * @param defaultValue the default value + * @return the long represented by the string, or the default if conversion fails + * @since 2.1 + */ + public static long toLong(final String str, final long defaultValue) { + if (str == null) { + return defaultValue; + } + try { + return Long.parseLong(str); + } catch (final NumberFormatException nfe) { + return defaultValue; + } + } + + /** + *

Convert a String to a float, returning + * 0.0f if the conversion fails.

+ * + *

If the string str is null, + * 0.0f is returned.

+ * + *
+     *   NumberUtils.toFloat(null)   = 0.0f
+     *   NumberUtils.toFloat("")     = 0.0f
+     *   NumberUtils.toFloat("1.5")  = 1.5f
+     * 
+ * + * @param str the string to convert, may be null + * @return the float represented by the string, or 0.0f + * if conversion fails + * @since 2.1 + */ + public static float toFloat(final String str) { + return toFloat(str, 0.0f); + } + + /** + *

Convert a String to a float, returning a + * default value if the conversion fails.

+ * + *

If the string str is null, the default + * value is returned.

+ * + *
+     *   NumberUtils.toFloat(null, 1.1f)   = 1.0f
+     *   NumberUtils.toFloat("", 1.1f)     = 1.1f
+     *   NumberUtils.toFloat("1.5", 0.0f)  = 1.5f
+     * 
+ * + * @param str the string to convert, may be null + * @param defaultValue the default value + * @return the float represented by the string, or defaultValue + * if conversion fails + * @since 2.1 + */ + public static float toFloat(final String str, final float defaultValue) { + if (str == null) { + return defaultValue; + } + try { + return Float.parseFloat(str); + } catch (final NumberFormatException nfe) { + return defaultValue; + } + } + + /** + *

Convert a String to a double, returning + * 0.0d if the conversion fails.

+ * + *

If the string str is null, + * 0.0d is returned.

+ * + *
+     *   NumberUtils.toDouble(null)   = 0.0d
+     *   NumberUtils.toDouble("")     = 0.0d
+     *   NumberUtils.toDouble("1.5")  = 1.5d
+     * 
+ * + * @param str the string to convert, may be null + * @return the double represented by the string, or 0.0d + * if conversion fails + * @since 2.1 + */ + public static double toDouble(final String str) { + return toDouble(str, 0.0d); + } + + /** + *

Convert a String to a double, returning a + * default value if the conversion fails.

+ * + *

If the string str is null, the default + * value is returned.

+ * + *
+     *   NumberUtils.toDouble(null, 1.1d)   = 1.1d
+     *   NumberUtils.toDouble("", 1.1d)     = 1.1d
+     *   NumberUtils.toDouble("1.5", 0.0d)  = 1.5d
+     * 
+ * + * @param str the string to convert, may be null + * @param defaultValue the default value + * @return the double represented by the string, or defaultValue + * if conversion fails + * @since 2.1 + */ + public static double toDouble(final String str, final double defaultValue) { + if (str == null) { + return defaultValue; + } + try { + return Double.parseDouble(str); + } catch (final NumberFormatException nfe) { + return defaultValue; + } + } + + //----------------------------------------------------------------------- + /** + *

Convert a String to a byte, returning + * zero if the conversion fails.

+ * + *

If the string is null, zero is returned.

+ * + *
+     *   NumberUtils.toByte(null) = 0
+     *   NumberUtils.toByte("")   = 0
+     *   NumberUtils.toByte("1")  = 1
+     * 
+ * + * @param str the string to convert, may be null + * @return the byte represented by the string, or zero if + * conversion fails + * @since 2.5 + */ + public static byte toByte(final String str) { + return toByte(str, (byte) 0); + } + + /** + *

Convert a String to a byte, returning a + * default value if the conversion fails.

+ * + *

If the string is null, the default value is returned.

+ * + *
+     *   NumberUtils.toByte(null, 1) = 1
+     *   NumberUtils.toByte("", 1)   = 1
+     *   NumberUtils.toByte("1", 0)  = 1
+     * 
+ * + * @param str the string to convert, may be null + * @param defaultValue the default value + * @return the byte represented by the string, or the default if conversion fails + * @since 2.5 + */ + public static byte toByte(final String str, final byte defaultValue) { + if(str == null) { + return defaultValue; + } + try { + return Byte.parseByte(str); + } catch (final NumberFormatException nfe) { + return defaultValue; + } + } + + /** + *

Convert a String to a short, returning + * zero if the conversion fails.

+ * + *

If the string is null, zero is returned.

+ * + *
+     *   NumberUtils.toShort(null) = 0
+     *   NumberUtils.toShort("")   = 0
+     *   NumberUtils.toShort("1")  = 1
+     * 
+ * + * @param str the string to convert, may be null + * @return the short represented by the string, or zero if + * conversion fails + * @since 2.5 + */ + public static short toShort(final String str) { + return toShort(str, (short) 0); + } + + /** + *

Convert a String to an short, returning a + * default value if the conversion fails.

+ * + *

If the string is null, the default value is returned.

+ * + *
+     *   NumberUtils.toShort(null, 1) = 1
+     *   NumberUtils.toShort("", 1)   = 1
+     *   NumberUtils.toShort("1", 0)  = 1
+     * 
+ * + * @param str the string to convert, may be null + * @param defaultValue the default value + * @return the short represented by the string, or the default if conversion fails + * @since 2.5 + */ + public static short toShort(final String str, final short defaultValue) { + if(str == null) { + return defaultValue; + } + try { + return Short.parseShort(str); + } catch (final NumberFormatException nfe) { + return defaultValue; + } + } + + //----------------------------------------------------------------------- + // must handle Long, Float, Integer, Float, Short, + // BigDecimal, BigInteger and Byte + // useful methods: + // Byte.decode(String) + // Byte.valueOf(String,int radix) + // Byte.valueOf(String) + // Double.valueOf(String) + // Float.valueOf(String) + // Float.valueOf(String) + // Integer.valueOf(String,int radix) + // Integer.valueOf(String) + // Integer.decode(String) + // Integer.getInteger(String) + // Integer.getInteger(String,int val) + // Integer.getInteger(String,Integer val) + // Integer.valueOf(String) + // Double.valueOf(String) + // new Byte(String) + // Long.valueOf(String) + // Long.getLong(String) + // Long.getLong(String,int) + // Long.getLong(String,Integer) + // Long.valueOf(String,int) + // Long.valueOf(String) + // Short.valueOf(String) + // Short.decode(String) + // Short.valueOf(String,int) + // Short.valueOf(String) + // new BigDecimal(String) + // new BigInteger(String) + // new BigInteger(String,int radix) + // Possible inputs: + // 45 45.5 45E7 4.5E7 Hex Oct Binary xxxF xxxD xxxf xxxd + // plus minus everything. Prolly more. A lot are not separable. + + /** + *

Turns a string value into a java.lang.Number.

+ * + *

If the string starts with {@code 0x} or {@code -0x} (lower or upper case) or {@code #} or {@code -#}, it + * will be interpreted as a hexadecimal Integer - or Long, if the number of digits after the + * prefix is more than 8 - or BigInteger if there are more than 16 digits. + *

+ *

Then, the value is examined for a type qualifier on the end, i.e. one of + * 'f','F','d','D','l','L'. If it is found, it starts + * trying to create successively larger types from the type specified + * until one is found that can represent the value.

+ * + *

If a type specifier is not found, it will check for a decimal point + * and then try successively larger types from Integer to + * BigInteger and from Float to + * BigDecimal.

+ * + *

+ * Integral values with a leading {@code 0} will be interpreted as octal; the returned number will + * be Integer, Long or BigDecimal as appropriate. + *

+ * + *

Returns null if the string is null.

+ * + *

This method does not trim the input string, i.e., strings with leading + * or trailing spaces will generate NumberFormatExceptions.

+ * + * @param str String containing a number, may be null + * @return Number created from the string (or null if the input is null) + * @throws NumberFormatException if the value cannot be converted + */ + public static Number createNumber(final String str) throws NumberFormatException { + if (str == null) { + return null; + } + if (StringUtils.isBlank(str)) { + throw new NumberFormatException("A blank string is not a valid number"); + } + // Need to deal with all possible hex prefixes here + final String[] hex_prefixes = {"0x", "0X", "-0x", "-0X", "#", "-#"}; + int pfxLen = 0; + for(final String pfx : hex_prefixes) { + if (str.startsWith(pfx)) { + pfxLen += pfx.length(); + break; + } + } + if (pfxLen > 0) { // we have a hex number + char firstSigDigit = 0; // strip leading zeroes + for(int i = pfxLen; i < str.length(); i++) { + firstSigDigit = str.charAt(i); + if (firstSigDigit == '0') { // count leading zeroes + pfxLen++; + } else { + break; + } + } + final int hexDigits = str.length() - pfxLen; + if (hexDigits > 16 || hexDigits == 16 && firstSigDigit > '7') { // too many for Long + return createBigInteger(str); + } + if (hexDigits > 8 || hexDigits == 8 && firstSigDigit > '7') { // too many for an int + return createLong(str); + } + return createInteger(str); + } + final char lastChar = str.charAt(str.length() - 1); + String mant; + String dec; + String exp; + final int decPos = str.indexOf('.'); + final int expPos = str.indexOf('e') + str.indexOf('E') + 1; // assumes both not present + // if both e and E are present, this is caught by the checks on expPos (which prevent IOOBE) + // and the parsing which will detect if e or E appear in a number due to using the wrong offset + + if (decPos > -1) { // there is a decimal point + if (expPos > -1) { // there is an exponent + if (expPos < decPos || expPos > str.length()) { // prevents double exponent causing IOOBE + throw new NumberFormatException(str + " is not a valid number."); + } + dec = str.substring(decPos + 1, expPos); + } else { + dec = str.substring(decPos + 1); + } + mant = getMantissa(str, decPos); + } else { + if (expPos > -1) { + if (expPos > str.length()) { // prevents double exponent causing IOOBE + throw new NumberFormatException(str + " is not a valid number."); + } + mant = getMantissa(str, expPos); + } else { + mant = getMantissa(str); + } + dec = null; + } + if (!Character.isDigit(lastChar) && lastChar != '.') { + if (expPos > -1 && expPos < str.length() - 1) { + exp = str.substring(expPos + 1, str.length() - 1); + } else { + exp = null; + } + //Requesting a specific type.. + final String numeric = str.substring(0, str.length() - 1); + final boolean allZeros = isAllZeros(mant) && isAllZeros(exp); + switch (lastChar) { + case 'l' : + case 'L' : + if (dec == null + && exp == null + && (numeric.charAt(0) == '-' && isDigits(numeric.substring(1)) || isDigits(numeric))) { + try { + return createLong(numeric); + } catch (final NumberFormatException nfe) { // NOPMD + // Too big for a long + } + return createBigInteger(numeric); + + } + throw new NumberFormatException(str + " is not a valid number."); + case 'f' : + case 'F' : + try { + final Float f = NumberUtils.createFloat(str); + if (!(f.isInfinite() || f.floatValue() == 0.0F && !allZeros)) { + //If it's too big for a float or the float value = 0 and the string + //has non-zeros in it, then float does not have the precision we want + return f; + } + + } catch (final NumberFormatException nfe) { // NOPMD + // ignore the bad number + } + //$FALL-THROUGH$ + case 'd' : + case 'D' : + try { + final Double d = NumberUtils.createDouble(str); + if (!(d.isInfinite() || d.floatValue() == 0.0D && !allZeros)) { + return d; + } + } catch (final NumberFormatException nfe) { // NOPMD + // ignore the bad number + } + try { + return createBigDecimal(numeric); + } catch (final NumberFormatException e) { // NOPMD + // ignore the bad number + } + //$FALL-THROUGH$ + default : + throw new NumberFormatException(str + " is not a valid number."); + + } + } + //User doesn't have a preference on the return type, so let's start + //small and go from there... + if (expPos > -1 && expPos < str.length() - 1) { + exp = str.substring(expPos + 1, str.length()); + } else { + exp = null; + } + if (dec == null && exp == null) { // no decimal point and no exponent + //Must be an Integer, Long, Biginteger + try { + return createInteger(str); + } catch (final NumberFormatException nfe) { // NOPMD + // ignore the bad number + } + try { + return createLong(str); + } catch (final NumberFormatException nfe) { // NOPMD + // ignore the bad number + } + return createBigInteger(str); + } + + //Must be a Float, Double, BigDecimal + final boolean allZeros = isAllZeros(mant) && isAllZeros(exp); + try { + final Float f = createFloat(str); + final Double d = createDouble(str); + if (!f.isInfinite() + && !(f.floatValue() == 0.0F && !allZeros) + && f.toString().equals(d.toString())) { + return f; + } + if (!d.isInfinite() && !(d.doubleValue() == 0.0D && !allZeros)) { + final BigDecimal b = createBigDecimal(str); + if (b.compareTo(BigDecimal.valueOf(d)) == 0) { + return d; + } + return b; + } + } catch (final NumberFormatException nfe) { // NOPMD + // ignore the bad number + } + return createBigDecimal(str); + } + + /** + *

Utility method for {@link #createNumber(java.lang.String)}.

+ * + *

Returns mantissa of the given number.

+ * + * @param str the string representation of the number + * @return mantissa of the given number + */ + private static String getMantissa(final String str) { + return getMantissa(str, str.length()); + } + + /** + *

Utility method for {@link #createNumber(java.lang.String)}.

+ * + *

Returns mantissa of the given number.

+ * + * @param str the string representation of the number + * @param stopPos the position of the exponent or decimal point + * @return mantissa of the given number + */ + private static String getMantissa(final String str, final int stopPos) { + final char firstChar = str.charAt(0); + final boolean hasSign = firstChar == '-' || firstChar == '+'; + + return hasSign ? str.substring(1, stopPos) : str.substring(0, stopPos); + } + + /** + *

Utility method for {@link #createNumber(java.lang.String)}.

+ * + *

Returns true if s is null.

+ * + * @param str the String to check + * @return if it is all zeros or null + */ + private static boolean isAllZeros(final String str) { + if (str == null) { + return true; + } + for (int i = str.length() - 1; i >= 0; i--) { + if (str.charAt(i) != '0') { + return false; + } + } + return str.length() > 0; + } + + //----------------------------------------------------------------------- + /** + *

Convert a String to a Float.

+ * + *

Returns null if the string is null.

+ * + * @param str a String to convert, may be null + * @return converted Float (or null if the input is null) + * @throws NumberFormatException if the value cannot be converted + */ + public static Float createFloat(final String str) { + if (str == null) { + return null; + } + return Float.valueOf(str); + } + + /** + *

Convert a String to a Double.

+ * + *

Returns null if the string is null.

+ * + * @param str a String to convert, may be null + * @return converted Double (or null if the input is null) + * @throws NumberFormatException if the value cannot be converted + */ + public static Double createDouble(final String str) { + if (str == null) { + return null; + } + return Double.valueOf(str); + } + + /** + *

Convert a String to a Integer, handling + * hex (0xhhhh) and octal (0dddd) notations. + * N.B. a leading zero means octal; spaces are not trimmed.

+ * + *

Returns null if the string is null.

+ * + * @param str a String to convert, may be null + * @return converted Integer (or null if the input is null) + * @throws NumberFormatException if the value cannot be converted + */ + public static Integer createInteger(final String str) { + if (str == null) { + return null; + } + // decode() handles 0xAABD and 0777 (hex and octal) as well. + return Integer.decode(str); + } + + /** + *

Convert a String to a Long; + * since 3.1 it handles hex (0Xhhhh) and octal (0ddd) notations. + * N.B. a leading zero means octal; spaces are not trimmed.

+ * + *

Returns null if the string is null.

+ * + * @param str a String to convert, may be null + * @return converted Long (or null if the input is null) + * @throws NumberFormatException if the value cannot be converted + */ + public static Long createLong(final String str) { + if (str == null) { + return null; + } + return Long.decode(str); + } + + /** + *

Convert a String to a BigInteger; + * since 3.2 it handles hex (0x or #) and octal (0) notations.

+ * + *

Returns null if the string is null.

+ * + * @param str a String to convert, may be null + * @return converted BigInteger (or null if the input is null) + * @throws NumberFormatException if the value cannot be converted + */ + public static BigInteger createBigInteger(final String str) { + if (str == null) { + return null; + } + int pos = 0; // offset within string + int radix = 10; + boolean negate = false; // need to negate later? + if (str.startsWith("-")) { + negate = true; + pos = 1; + } + if (str.startsWith("0x", pos) || str.startsWith("0X", pos)) { // hex + radix = 16; + pos += 2; + } else if (str.startsWith("#", pos)) { // alternative hex (allowed by Long/Integer) + radix = 16; + pos ++; + } else if (str.startsWith("0", pos) && str.length() > pos + 1) { // octal; so long as there are additional digits + radix = 8; + pos ++; + } // default is to treat as decimal + + final BigInteger value = new BigInteger(str.substring(pos), radix); + return negate ? value.negate() : value; + } + + /** + *

Convert a String to a BigDecimal.

+ * + *

Returns null if the string is null.

+ * + * @param str a String to convert, may be null + * @return converted BigDecimal (or null if the input is null) + * @throws NumberFormatException if the value cannot be converted + */ +/** + *

Convert a String to a BigDecimal.

+ * + *

Returns null if the string is null.

+ * + * @param str + * a String to convert, may be null + * @return converted BigDecimal (or null if the input is null) + * @throws NumberFormatException + * if the value cannot be converted + */ +public static java.math.BigDecimal createBigDecimal(final java.lang.String str) { + { + // handle JDK1.3.1 bug where "" throws IndexOutOfBoundsException + if (org.apache.commons.lang3.StringUtils.isBlank(/* NPEX_NULL_EXP */ + str)) { + throw new java.lang.NumberFormatException("A blank string is not a valid number"); + } + if (str.trim().startsWith("--")) { + // this is protection for poorness in java.lang.BigDecimal. + // it accepts this as a legal value, but it does not appear + // to be in specification of class. OS X Java parses it to + // a wrong value. + throw new java.lang.NumberFormatException(str + " is not a valid number."); + } + return new java.math.BigDecimal(str); + } +} + + // Min in array + //-------------------------------------------------------------------- + /** + *

Returns the minimum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the minimum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @since 3.4 Changed signature from min(long[]) to min(long...) + */ + public static long min(final long... array) { + // Validates input + validateArray(array); + + // Finds and returns min + long min = array[0]; + for (int i = 1; i < array.length; i++) { + if (array[i] < min) { + min = array[i]; + } + } + + return min; + } + + /** + *

Returns the minimum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the minimum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @since 3.4 Changed signature from min(int[]) to min(int...) + */ + public static int min(final int... array) { + // Validates input + validateArray(array); + + // Finds and returns min + int min = array[0]; + for (int j = 1; j < array.length; j++) { + if (array[j] < min) { + min = array[j]; + } + } + + return min; + } + + /** + *

Returns the minimum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the minimum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @since 3.4 Changed signature from min(short[]) to min(short...) + */ + public static short min(final short... array) { + // Validates input + validateArray(array); + + // Finds and returns min + short min = array[0]; + for (int i = 1; i < array.length; i++) { + if (array[i] < min) { + min = array[i]; + } + } + + return min; + } + + /** + *

Returns the minimum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the minimum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @since 3.4 Changed signature from min(byte[]) to min(byte...) + */ + public static byte min(final byte... array) { + // Validates input + validateArray(array); + + // Finds and returns min + byte min = array[0]; + for (int i = 1; i < array.length; i++) { + if (array[i] < min) { + min = array[i]; + } + } + + return min; + } + + /** + *

Returns the minimum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the minimum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @see IEEE754rUtils#min(double[]) IEEE754rUtils for a version of this method that handles NaN differently + * @since 3.4 Changed signature from min(double[]) to min(double...) + */ + public static double min(final double... array) { + // Validates input + validateArray(array); + + // Finds and returns min + double min = array[0]; + for (int i = 1; i < array.length; i++) { + if (Double.isNaN(array[i])) { + return Double.NaN; + } + if (array[i] < min) { + min = array[i]; + } + } + + return min; + } + + /** + *

Returns the minimum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the minimum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @see IEEE754rUtils#min(float[]) IEEE754rUtils for a version of this method that handles NaN differently + * @since 3.4 Changed signature from min(float[]) to min(float...) + */ + public static float min(final float... array) { + // Validates input + validateArray(array); + + // Finds and returns min + float min = array[0]; + for (int i = 1; i < array.length; i++) { + if (Float.isNaN(array[i])) { + return Float.NaN; + } + if (array[i] < min) { + min = array[i]; + } + } + + return min; + } + + // Max in array + //-------------------------------------------------------------------- + /** + *

Returns the maximum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the maximum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @since 3.4 Changed signature from max(long[]) to max(long...) + */ + public static long max(final long... array) { + // Validates input + validateArray(array); + + // Finds and returns max + long max = array[0]; + for (int j = 1; j < array.length; j++) { + if (array[j] > max) { + max = array[j]; + } + } + + return max; + } + + /** + *

Returns the maximum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the maximum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @since 3.4 Changed signature from max(int[]) to max(int...) + */ + public static int max(final int... array) { + // Validates input + validateArray(array); + + // Finds and returns max + int max = array[0]; + for (int j = 1; j < array.length; j++) { + if (array[j] > max) { + max = array[j]; + } + } + + return max; + } + + /** + *

Returns the maximum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the maximum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @since 3.4 Changed signature from max(short[]) to max(short...) + */ + public static short max(final short... array) { + // Validates input + validateArray(array); + + // Finds and returns max + short max = array[0]; + for (int i = 1; i < array.length; i++) { + if (array[i] > max) { + max = array[i]; + } + } + + return max; + } + + /** + *

Returns the maximum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the maximum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @since 3.4 Changed signature from max(byte[]) to max(byte...) + */ + public static byte max(final byte... array) { + // Validates input + validateArray(array); + + // Finds and returns max + byte max = array[0]; + for (int i = 1; i < array.length; i++) { + if (array[i] > max) { + max = array[i]; + } + } + + return max; + } + + /** + *

Returns the maximum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the maximum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @see IEEE754rUtils#max(double[]) IEEE754rUtils for a version of this method that handles NaN differently + * @since 3.4 Changed signature from max(double[]) to max(double...) + */ + public static double max(final double... array) { + // Validates input + validateArray(array); + + // Finds and returns max + double max = array[0]; + for (int j = 1; j < array.length; j++) { + if (Double.isNaN(array[j])) { + return Double.NaN; + } + if (array[j] > max) { + max = array[j]; + } + } + + return max; + } + + /** + *

Returns the maximum value in an array.

+ * + * @param array an array, must not be null or empty + * @return the maximum value in the array + * @throws IllegalArgumentException if array is null + * @throws IllegalArgumentException if array is empty + * @see IEEE754rUtils#max(float[]) IEEE754rUtils for a version of this method that handles NaN differently + * @since 3.4 Changed signature from max(float[]) to max(float...) + */ + public static float max(final float... array) { + // Validates input + validateArray(array); + + // Finds and returns max + float max = array[0]; + for (int j = 1; j < array.length; j++) { + if (Float.isNaN(array[j])) { + return Float.NaN; + } + if (array[j] > max) { + max = array[j]; + } + } + + return max; + } + + /** + * Checks if the specified array is neither null nor empty. + * + * @param array the array to check + * @throws IllegalArgumentException if {@code array} is either {@code null} or empty + */ + private static void validateArray(final Object array) { + if (array == null) { + throw new IllegalArgumentException("The Array must not be null"); + } + Validate.isTrue(Array.getLength(array) != 0, "Array cannot be empty."); + } + + // 3 param min + //----------------------------------------------------------------------- + /** + *

Gets the minimum of three long values.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the smallest of the values + */ + public static long min(long a, final long b, final long c) { + if (b < a) { + a = b; + } + if (c < a) { + a = c; + } + return a; + } + + /** + *

Gets the minimum of three int values.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the smallest of the values + */ + public static int min(int a, final int b, final int c) { + if (b < a) { + a = b; + } + if (c < a) { + a = c; + } + return a; + } + + /** + *

Gets the minimum of three short values.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the smallest of the values + */ + public static short min(short a, final short b, final short c) { + if (b < a) { + a = b; + } + if (c < a) { + a = c; + } + return a; + } + + /** + *

Gets the minimum of three byte values.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the smallest of the values + */ + public static byte min(byte a, final byte b, final byte c) { + if (b < a) { + a = b; + } + if (c < a) { + a = c; + } + return a; + } + + /** + *

Gets the minimum of three double values.

+ * + *

If any value is NaN, NaN is + * returned. Infinity is handled.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the smallest of the values + * @see IEEE754rUtils#min(double, double, double) for a version of this method that handles NaN differently + */ + public static double min(final double a, final double b, final double c) { + return Math.min(Math.min(a, b), c); + } + + /** + *

Gets the minimum of three float values.

+ * + *

If any value is NaN, NaN is + * returned. Infinity is handled.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the smallest of the values + * @see IEEE754rUtils#min(float, float, float) for a version of this method that handles NaN differently + */ + public static float min(final float a, final float b, final float c) { + return Math.min(Math.min(a, b), c); + } + + // 3 param max + //----------------------------------------------------------------------- + /** + *

Gets the maximum of three long values.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the largest of the values + */ + public static long max(long a, final long b, final long c) { + if (b > a) { + a = b; + } + if (c > a) { + a = c; + } + return a; + } + + /** + *

Gets the maximum of three int values.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the largest of the values + */ + public static int max(int a, final int b, final int c) { + if (b > a) { + a = b; + } + if (c > a) { + a = c; + } + return a; + } + + /** + *

Gets the maximum of three short values.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the largest of the values + */ + public static short max(short a, final short b, final short c) { + if (b > a) { + a = b; + } + if (c > a) { + a = c; + } + return a; + } + + /** + *

Gets the maximum of three byte values.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the largest of the values + */ + public static byte max(byte a, final byte b, final byte c) { + if (b > a) { + a = b; + } + if (c > a) { + a = c; + } + return a; + } + + /** + *

Gets the maximum of three double values.

+ * + *

If any value is NaN, NaN is + * returned. Infinity is handled.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the largest of the values + * @see IEEE754rUtils#max(double, double, double) for a version of this method that handles NaN differently + */ + public static double max(final double a, final double b, final double c) { + return Math.max(Math.max(a, b), c); + } + + /** + *

Gets the maximum of three float values.

+ * + *

If any value is NaN, NaN is + * returned. Infinity is handled.

+ * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the largest of the values + * @see IEEE754rUtils#max(float, float, float) for a version of this method that handles NaN differently + */ + public static float max(final float a, final float b, final float c) { + return Math.max(Math.max(a, b), c); + } + + //----------------------------------------------------------------------- + /** + *

Checks whether the String contains only + * digit characters.

+ * + *

Null and empty String will return + * false.

+ * + * @param str the String to check + * @return true if str contains only Unicode numeric + */ + public static boolean isDigits(final String str) { + return StringUtils.isNumeric(str); + } + + /** + *

Checks whether the String a valid Java number.

+ * + *

Valid numbers include hexadecimal marked with the 0x or + * 0X qualifier, octal numbers, scientific notation and + * numbers marked with a type qualifier (e.g. 123L).

+ * + *

Non-hexadecimal strings beginning with a leading zero are + * treated as octal values. Thus the string 09 will return + * false, since 9 is not a valid octal value. + * However, numbers beginning with {@code 0.} are treated as decimal.

+ * + *

null and empty/blank {@code String} will return + * false.

+ * + *

Note, {@link #createNumber(String)} should return a number for every + * input resuling in true.

+ * + * @param str the String to check + * @return true if the string is a correctly formatted number + * @since 3.3 the code supports hex {@code 0Xhhh} an + * octal {@code 0ddd} validation + * @deprecated This feature will be removed in Lang 4.0, + * use {@link NumberUtils#isCreatable(String)} instead + */ + @Deprecated + public static boolean isNumber(final String str) { + return isCreatable(str); + } + + /** + *

Checks whether the String a valid Java number.

+ * + *

Valid numbers include hexadecimal marked with the 0x or + * 0X qualifier, octal numbers, scientific notation and + * numbers marked with a type qualifier (e.g. 123L).

+ * + *

Non-hexadecimal strings beginning with a leading zero are + * treated as octal values. Thus the string 09 will return + * false, since 9 is not a valid octal value. + * However, numbers beginning with {@code 0.} are treated as decimal.

+ * + *

null and empty/blank {@code String} will return + * false.

+ * + *

Note, {@link #createNumber(String)} should return a number for every + * input resuling in true.

+ * + * @param str the String to check + * @return true if the string is a correctly formatted number + * @since 3.5 the code supports the "+" suffix on numbers except for integers in Java 1.6 + */ + public static boolean isCreatable(final String str) { + if (StringUtils.isEmpty(str)) { + return false; + } + final char[] chars = str.toCharArray(); + int sz = chars.length; + boolean hasExp = false; + boolean hasDecPoint = false; + boolean allowSigns = false; + boolean foundDigit = false; + // deal with any possible sign up front + final int start = chars[0] == '-' || chars[0] == '+' ? 1 : 0; + final boolean hasLeadingPlusSign = start == 1 && chars[0] == '+'; + if (sz > start + 1 && chars[start] == '0') { // leading 0 + if (chars[start + 1] == 'x' || chars[start + 1] == 'X') { // leading 0x/0X + int i = start + 2; + if (i == sz) { + return false; // str == "0x" + } + // checking hex (it can't be anything else) + for (; i < chars.length; i++) { + if ((chars[i] < '0' || chars[i] > '9') + && (chars[i] < 'a' || chars[i] > 'f') + && (chars[i] < 'A' || chars[i] > 'F')) { + return false; + } + } + return true; + } else if (Character.isDigit(chars[start + 1])) { + // leading 0, but not hex, must be octal + int i = start + 1; + for (; i < chars.length; i++) { + if (chars[i] < '0' || chars[i] > '7') { + return false; + } + } + return true; + } + } + sz--; // don't want to loop to the last char, check it afterwords + // for type qualifiers + int i = start; + // loop to the next to last char or to the last char if we need another digit to + // make a valid number (e.g. chars[0..5] = "1234E") + while (i < sz || i < sz + 1 && allowSigns && !foundDigit) { + if (chars[i] >= '0' && chars[i] <= '9') { + foundDigit = true; + allowSigns = false; + + } else if (chars[i] == '.') { + if (hasDecPoint || hasExp) { + // two decimal points or dec in exponent + return false; + } + hasDecPoint = true; + } else if (chars[i] == 'e' || chars[i] == 'E') { + // we've already taken care of hex. + if (hasExp) { + // two E's + return false; + } + if (!foundDigit) { + return false; + } + hasExp = true; + allowSigns = true; + } else if (chars[i] == '+' || chars[i] == '-') { + if (!allowSigns) { + return false; + } + allowSigns = false; + foundDigit = false; // we need a digit after the E + } else { + return false; + } + i++; + } + if (i < chars.length) { + if (chars[i] >= '0' && chars[i] <= '9') { + if (SystemUtils.IS_JAVA_1_6 && hasLeadingPlusSign && !hasDecPoint) { + return false; + } + // no type qualifier, OK + return true; + } + if (chars[i] == 'e' || chars[i] == 'E') { + // can't have an E at the last byte + return false; + } + if (chars[i] == '.') { + if (hasDecPoint || hasExp) { + // two decimal points or dec in exponent + return false; + } + // single trailing decimal point after non-exponent is ok + return foundDigit; + } + if (!allowSigns + && (chars[i] == 'd' + || chars[i] == 'D' + || chars[i] == 'f' + || chars[i] == 'F')) { + return foundDigit; + } + if (chars[i] == 'l' + || chars[i] == 'L') { + // not allowing L with an exponent or decimal point + return foundDigit && !hasExp && !hasDecPoint; + } + // last character is illegal + return false; + } + // allowSigns is true iff the val ends in 'E' + // found digit it to make sure weird stuff like '.' and '1E-' doesn't pass + return !allowSigns && foundDigit; + } + + /** + *

Checks whether the given String is a parsable number.

+ * + *

Parsable numbers include those Strings understood by {@link Integer#parseInt(String)}, + * {@link Long#parseLong(String)}, {@link Float#parseFloat(String)} or + * {@link Double#parseDouble(String)}. This method can be used instead of catching {@link java.text.ParseException} + * when calling one of those methods.

+ * + *

Hexadecimal and scientific notations are not considered parsable. + * See {@link #isCreatable(String)} on those cases.

+ * + *

{@code Null} and empty String will return false.

+ * + * @param str the String to check. + * @return {@code true} if the string is a parsable number. + * @since 3.4 + */ + public static boolean isParsable(final String str) { + if (StringUtils.isEmpty(str)) { + return false; + } + if (str.charAt(str.length() - 1) == '.') { + return false; + } + if (str.charAt(0) == '-') { + if (str.length() == 1) { + return false; + } + return withDecimalsParsing(str, 1); + } else { + return withDecimalsParsing(str, 0); + } + } + + private static boolean withDecimalsParsing(final String str, final int beginIdx) { + int decimalPoints = 0; + for (int i = beginIdx; i < str.length(); i++) { + final boolean isDecimalPoint = str.charAt(i) == '.'; + if (isDecimalPoint) { + decimalPoints++; + } + if (decimalPoints > 1) { + return false; + } + if (!isDecimalPoint && !Character.isDigit(str.charAt(i))) { + return false; + } + } + return true; + } + + /** + *

Compares two {@code int} values numerically. This is the same functionality as provided in Java 7.

+ * + * @param x the first {@code int} to compare + * @param y the second {@code int} 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(int x, int y) { + if (x == y) { + return 0; + } + return x < y ? -1 : 1; + } + + /** + *

Compares to {@code long} values numerically. This is the same functionality as provided in Java 7.

+ * + * @param x the first {@code long} to compare + * @param y the second {@code long} 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(long x, long y) { + if (x == y) { + return 0; + } + return x < y ? -1 : 1; + } + + /** + *

Compares to {@code short} values numerically. This is the same functionality as provided in Java 7.

+ * + * @param x the first {@code short} to compare + * @param y the second {@code short} 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(short x, short y) { + if (x == y) { + return 0; + } + return x < y ? -1 : 1; + } + + /** + *

Compares two {@code byte} values numerically. This is the same functionality as provided in Java 7.

+ * + * @param x the first {@code byte} to compare + * @param y the second {@code byte} 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(byte x, byte y) { + return x - y; + } +} diff --git a/Java/commons-lang-NumberUtils_784/metadata.json b/Java/commons-lang-NumberUtils_784/metadata.json new file mode 100644 index 000000000..c44b8a8b0 --- /dev/null +++ b/Java/commons-lang-NumberUtils_784/metadata.json @@ -0,0 +1,21 @@ +{ + "language": "java", + "id": "commons-lang-NumberUtils_784", + "buggyPath": ".", + "referencePath": null, + "buildCommand": "mvn package -V -B -Denforcer.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true -Drat.skip=true -Dlicense.skip=true -Dfindbugs.skip=true -Dgpg.skip=true -Dskip.npm=true -Dskip.gulp=true -Dskip.bower=true -Drat.numUnapprovedLicenses=100 -DskipTests=true -DskipITs=true -Dtest=None -DfailIfNoTests=false", + "testCommand": "mvn test -V -B -Denforcer.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true -Drat.skip=true -Dlicense.skip=true -Dfindbugs.skip=true -Dgpg.skip=true -Dskip.npm=true -Dskip.gulp=true -Dskip.bower=true -Drat.numUnapprovedLicenses=100", + "categories": [ + "safety", + "npe" + ], + "npe": { + "filepath": "src/main/java/org/apache/commons/lang3/math/NumberUtils.java", + "line": 798, + "npe_method": "createBigDecimal", + "deref_field": "str", + "npe_class": "NumberUtils", + "repo": "commons-lang", + "bug_id": "NumberUtils_784" + } +} diff --git a/Java/commons-lang-NumberUtils_784/npe.json b/Java/commons-lang-NumberUtils_784/npe.json new file mode 100644 index 000000000..25b6008c4 --- /dev/null +++ b/Java/commons-lang-NumberUtils_784/npe.json @@ -0,0 +1,7 @@ +{ + "filepath": "src/main/java/org/apache/commons/lang3/math/NumberUtils.java", + "line": 798, + "npe_method": "createBigDecimal", + "deref_field": "str", + "npe_class": "NumberUtils" +} \ No newline at end of file From 517cc5e7f55f69e3f1556b331b75140cefc77d52 Mon Sep 17 00:00:00 2001 From: Seokhyun Lee <7948302+henrylee97@users.noreply.github.com> Date: Fri, 1 Dec 2023 09:58:38 +0900 Subject: [PATCH 2/4] refactor(java): commons-lang W-classes (#147) --- Java/commons-lang-WordUtils_269/Dockerfile | 18 + Java/commons-lang-WordUtils_269/buggy.java | 822 ++++++++++++++++++ Java/commons-lang-WordUtils_269/metadata.json | 21 + Java/commons-lang-WordUtils_269/npe.json | 7 + Java/commons-lang-WordUtils_403/Dockerfile | 18 + Java/commons-lang-WordUtils_403/buggy.java | 769 ++++++++++++++++ Java/commons-lang-WordUtils_403/metadata.json | 21 + Java/commons-lang-WordUtils_403/npe.json | 7 + Java/commons-lang-WordUtils_726/Dockerfile | 18 + Java/commons-lang-WordUtils_726/buggy.java | 747 ++++++++++++++++ Java/commons-lang-WordUtils_726/metadata.json | 21 + Java/commons-lang-WordUtils_726/npe.json | 7 + 12 files changed, 2476 insertions(+) create mode 100644 Java/commons-lang-WordUtils_269/Dockerfile create mode 100644 Java/commons-lang-WordUtils_269/buggy.java create mode 100644 Java/commons-lang-WordUtils_269/metadata.json create mode 100644 Java/commons-lang-WordUtils_269/npe.json create mode 100644 Java/commons-lang-WordUtils_403/Dockerfile create mode 100644 Java/commons-lang-WordUtils_403/buggy.java create mode 100644 Java/commons-lang-WordUtils_403/metadata.json create mode 100644 Java/commons-lang-WordUtils_403/npe.json create mode 100644 Java/commons-lang-WordUtils_726/Dockerfile create mode 100644 Java/commons-lang-WordUtils_726/buggy.java create mode 100644 Java/commons-lang-WordUtils_726/metadata.json create mode 100644 Java/commons-lang-WordUtils_726/npe.json diff --git a/Java/commons-lang-WordUtils_269/Dockerfile b/Java/commons-lang-WordUtils_269/Dockerfile new file mode 100644 index 000000000..7b7fbe349 --- /dev/null +++ b/Java/commons-lang-WordUtils_269/Dockerfile @@ -0,0 +1,18 @@ +FROM ghcr.io/kupl/starlab-benchmarks/java-base:commons-lang + +ENV TZ=Asia/Seoul + +COPY ./metadata.json . +COPY ./npe.json . +COPY ./buggy.java /tmp/buggy.java +RUN export BUGGY_PATH=$(cat metadata.json | jq -r ".npe.filepath") \ + && export BUGGY_LINE=$(cat metadata.json | jq -r ".npe.line") \ + && export BUGGY_MTHD=$(cat metadata.json | jq -r ".npe.npe_method") \ + && mv /tmp/buggy.java $BUGGY_PATH \ + && echo "[{\"filepath\": \"$BUGGY_PATH\", \"line\": $BUGGY_LINE, \"method_name\": \"$BUGGY_MTHD\"}]" | jq . > traces.json + +RUN git init . && git add -A + +RUN $(cat metadata.json | jq -r ".buildCommand") + +RUN $(cat metadata.json | jq -r ".testCommand"); if [ $? -eq 0 ]; then exit 1; fi diff --git a/Java/commons-lang-WordUtils_269/buggy.java b/Java/commons-lang-WordUtils_269/buggy.java new file mode 100644 index 000000000..2cdb49c94 --- /dev/null +++ b/Java/commons-lang-WordUtils_269/buggy.java @@ -0,0 +1,822 @@ +/* + * 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.text; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.apache.commons.lang3.ArrayUtils; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.SystemUtils; + +/** + *

Operations on Strings that contain words.

+ * + *

This class tries to handle null input gracefully. + * An exception will not be thrown for a null input. + * Each method documents its behaviour in more detail.

+ * + * @since 2.0 + */ +public class WordUtils { + + /** + *

WordUtils instances should NOT be constructed in + * standard programming. Instead, the class should be used as + * WordUtils.wrap("foo bar", 20);.

+ * + *

This constructor is public to permit tools that require a JavaBean + * instance to operate.

+ */ + public WordUtils() { + super(); + } + + // Wrapping + //-------------------------------------------------------------------------- + /** + *

Wraps a single line of text, identifying words by ' '.

+ * + *

New lines will be separated by the system property line separator. + * Very long words, such as URLs will not be wrapped.

+ * + *

Leading spaces on a new line are stripped. + * Trailing spaces are not stripped.

+ * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
inputwrapLengthresult
null*null
""*""
"Here is one line of text that is going to be wrapped after 20 columns."20"Here is one line of\ntext that is going\nto be wrapped after\n20 columns."
"Click here to jump to the commons website - http://commons.apache.org"20"Click here to jump\nto the commons\nwebsite -\nhttp://commons.apache.org"
"Click here, http://commons.apache.org, to jump to the commons website"20"Click here,\nhttp://commons.apache.org,\nto jump to the\ncommons website"
+ * + * (assuming that '\n' is the systems line separator) + * + * @param str the String to be word wrapped, may be null + * @param wrapLength the column to wrap the words at, less than 1 is treated as 1 + * @return a line with newlines inserted, null if null input + */ + public static String wrap(final String str, final int wrapLength) { + return wrap(str, wrapLength, null, false); + } + + /** + *

Wraps a single line of text, identifying words by ' '.

+ * + *

Leading spaces on a new line are stripped. + * Trailing spaces are not stripped.

+ * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
inputwrapLenghtnewLineStringwrapLongWordsresult
null**true/falsenull
""**true/false""
"Here is one line of text that is going to be wrapped after 20 columns."20"\n"true/false"Here is one line of\ntext that is going\nto be wrapped after\n20 columns."
"Here is one line of text that is going to be wrapped after 20 columns."20"<br />"true/false"Here is one line of<br />text that is going<br />to be wrapped after<br />20 columns."
"Here is one line of text that is going to be wrapped after 20 columns."20nulltrue/false"Here is one line of" + systemNewLine + "text that is going" + systemNewLine + "to be wrapped after" + systemNewLine + "20 columns."
"Click here to jump to the commons website - http://commons.apache.org"20"\n"false"Click here to jump\nto the commons\nwebsite -\nhttp://commons.apache.org"
"Click here to jump to the commons website - http://commons.apache.org"20"\n"true"Click here to jump\nto the commons\nwebsite -\nhttp://commons.apach\ne.org"
+ * + * @param str the String to be word wrapped, may be null + * @param wrapLength the column to wrap the words at, less than 1 is treated as 1 + * @param newLineStr the string to insert for a new line, + * null uses the system property line separator + * @param wrapLongWords true if long words (such as URLs) should be wrapped + * @return a line with newlines inserted, null if null input + */ + public static String wrap(final String str, int wrapLength, String newLineStr, final boolean wrapLongWords) { + return wrap(str, wrapLength, newLineStr, wrapLongWords, " "); + } + + /** + *

Wraps a single line of text, identifying words by wrapOn.

+ * + *

Leading spaces on a new line are stripped. + * Trailing spaces are not stripped.

+ * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
inputwrapLenghtnewLineStringwrapLongWordswrapOnresult
null**true/false*null
""**true/false*""
"Here is one line of text that is going to be wrapped after 20 columns."20"\n"true/false" ""Here is one line of\ntext that is going\nto be wrapped after\n20 columns."
"Here is one line of text that is going to be wrapped after 20 columns."20"<br />"true/false" ""Here is one line of<br />text that is going<br />to be wrapped after<br />20 columns."
"Here is one line of text that is going to be wrapped after 20 columns."20nulltrue/false" ""Here is one line of" + systemNewLine + "text that is going" + systemNewLine + "to be wrapped after" + systemNewLine + "20 columns."
"Click here to jump to the commons website - http://commons.apache.org"20"\n"false" ""Click here to jump\nto the commons\nwebsite -\nhttp://commons.apache.org"
"Click here to jump to the commons website - http://commons.apache.org"20"\n"true" ""Click here to jump\nto the commons\nwebsite -\nhttp://commons.apach\ne.org"
"flammable/inflammable"20"\n"true"/""flammable\ninflammable"
+ * @param str the String to be word wrapped, may be null + * @param wrapLength the column to wrap the words at, less than 1 is treated as 1 + * @param newLineStr the string to insert for a new line, + * null uses the system property line separator + * @param wrapLongWords true if long words (such as URLs) should be wrapped + * @param wrapOn regex expression to be used as a breakable characters, + * if blank string is provided a space character will be used + * @return a line with newlines inserted, null if null input + */ +/** + *

Wraps a single line of text, identifying words by wrapOn.

+ * + *

Leading spaces on a new line are stripped. + * Trailing spaces are not stripped.

+ * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
inputwrapLenghtnewLineStringwrapLongWordswrapOnresult
null**true/false*null
""**true/false*""
"Here is one line of text that is going to be wrapped after 20 columns."20"\n"true/false" ""Here is one line of\ntext that is going\nto be wrapped after\n20 columns."
"Here is one line of text that is going to be wrapped after 20 columns."20"<br />"true/false" ""Here is one line of<br />text that is going<br />to be wrapped after<br />20 columns."
"Here is one line of text that is going to be wrapped after 20 columns."20nulltrue/false" ""Here is one line of" + systemNewLine + "text that is going" + systemNewLine + "to be wrapped after" + systemNewLine + "20 columns."
"Click here to jump to the commons website - http://commons.apache.org"20"\n"false" ""Click here to jump\nto the commons\nwebsite -\nhttp://commons.apache.org"
"Click here to jump to the commons website - http://commons.apache.org"20"\n"true" ""Click here to jump\nto the commons\nwebsite -\nhttp://commons.apach\ne.org"
"flammable/inflammable"20"\n"true"/""flammable\ninflammable"
+ * + * @param str + * the String to be word wrapped, may be null + * @param wrapLength + * the column to wrap the words at, less than 1 is treated as 1 + * @param newLineStr + * the string to insert for a new line, + * null uses the system property line separator + * @param wrapLongWords + * true if long words (such as URLs) should be wrapped + * @param wrapOn + * regex expression to be used as a breakable characters, + * if blank string is provided a space character will be used + * @return a line with newlines inserted, null if null input + */ +public static java.lang.String wrap(final java.lang.String str, int wrapLength, java.lang.String newLineStr, final boolean wrapLongWords, java.lang.String wrapOn) { + { + if (newLineStr == null) { + newLineStr = org.apache.commons.lang3.SystemUtils.LINE_SEPARATOR; + } + if (wrapLength < 1) { + wrapLength = 1; + } + if (org.apache.commons.lang3.StringUtils.isBlank(wrapOn)) { + wrapOn = " "; + } + java.util.regex.Pattern patternToWrapOn = java.util.regex.Pattern.compile(wrapOn); + final int inputLineLength = /* NPEX_NULL_EXP */ + str.length(); + int offset = 0; + final java.lang.StringBuilder wrappedLine = new java.lang.StringBuilder(inputLineLength + 32); + while (offset < inputLineLength) { + int spaceToWrapAt = -1; + java.util.regex.Matcher matcher = patternToWrapOn.matcher(str.substring(offset, java.lang.Math.min((offset + wrapLength) + 1, inputLineLength))); + if (matcher.find()) { + if (matcher.start() == 0) { + offset += matcher.end(); + continue; + } else { + spaceToWrapAt = matcher.start(); + } + } + // only last line without leading spaces is left + if ((inputLineLength - offset) <= wrapLength) { + break; + } + while (matcher.find()) { + spaceToWrapAt = matcher.start() + offset; + } + if (spaceToWrapAt >= offset) { + // normal case + wrappedLine.append(str.substring(offset, spaceToWrapAt)); + wrappedLine.append(newLineStr); + offset = spaceToWrapAt + 1; + } else // really long word or URL + if (wrapLongWords) { + // wrap really long word one line at a time + wrappedLine.append(str.substring(offset, wrapLength + offset)); + wrappedLine.append(newLineStr); + offset += wrapLength; + } else { + // do not wrap really long word, just extend beyond limit + matcher = patternToWrapOn.matcher(str.substring(offset + wrapLength)); + if (matcher.find()) { + spaceToWrapAt = (matcher.start() + offset) + wrapLength; + } + if (spaceToWrapAt >= 0) { + wrappedLine.append(str.substring(offset, spaceToWrapAt)); + wrappedLine.append(newLineStr); + offset = spaceToWrapAt + 1; + } else { + wrappedLine.append(str.substring(offset)); + offset = inputLineLength; + } + } + } + // Whatever is left in line is short enough to just pass through + wrappedLine.append(str.substring(offset)); + return wrappedLine.toString(); + } +} + + // Capitalizing + //----------------------------------------------------------------------- + /** + *

Capitalizes all the whitespace separated words in a String. + * Only the first character of each word is changed. To convert the + * rest of each word to lowercase at the same time, + * use {@link #capitalizeFully(String)}.

+ * + *

Whitespace is defined by {@link Character#isWhitespace(char)}. + * A null input String returns null. + * Capitalization uses the Unicode title case, normally equivalent to + * upper case.

+ * + *
+     * WordUtils.capitalize(null)        = null
+     * WordUtils.capitalize("")          = ""
+     * WordUtils.capitalize("i am FINE") = "I Am FINE"
+     * 
+ * + * @param str the String to capitalize, may be null + * @return capitalized String, null if null String input + * @see #uncapitalize(String) + * @see #capitalizeFully(String) + */ + public static String capitalize(final String str) { + return capitalize(str, null); + } + + /** + *

Capitalizes all the delimiter separated words in a String. + * Only the first character of each word is changed. To convert the + * rest of each word to lowercase at the same time, + * use {@link #capitalizeFully(String, char[])}.

+ * + *

The delimiters represent a set of characters understood to separate words. + * The first string character and the first non-delimiter character after a + * delimiter will be capitalized.

+ * + *

A null input String returns null. + * Capitalization uses the Unicode title case, normally equivalent to + * upper case.

+ * + *
+     * WordUtils.capitalize(null, *)            = null
+     * WordUtils.capitalize("", *)              = ""
+     * WordUtils.capitalize(*, new char[0])     = *
+     * WordUtils.capitalize("i am fine", null)  = "I Am Fine"
+     * WordUtils.capitalize("i aM.fine", {'.'}) = "I aM.Fine"
+     * 
+ * + * @param str the String to capitalize, may be null + * @param delimiters set of characters to determine capitalization, null means whitespace + * @return capitalized String, null if null String input + * @see #uncapitalize(String) + * @see #capitalizeFully(String) + * @since 2.1 + */ + public static String capitalize(final String str, final char... delimiters) { + final int delimLen = delimiters == null ? -1 : delimiters.length; + if (StringUtils.isEmpty(str) || delimLen == 0) { + return str; + } + final char[] buffer = str.toCharArray(); + boolean capitalizeNext = true; + for (int i = 0; i < buffer.length; i++) { + final char ch = buffer[i]; + if (isDelimiter(ch, delimiters)) { + capitalizeNext = true; + } else if (capitalizeNext) { + buffer[i] = Character.toTitleCase(ch); + capitalizeNext = false; + } + } + return new String(buffer); + } + + //----------------------------------------------------------------------- + /** + *

Converts all the whitespace separated words in a String into capitalized words, + * that is each word is made up of a titlecase character and then a series of + * lowercase characters.

+ * + *

Whitespace is defined by {@link Character#isWhitespace(char)}. + * A null input String returns null. + * Capitalization uses the Unicode title case, normally equivalent to + * upper case.

+ * + *
+     * WordUtils.capitalizeFully(null)        = null
+     * WordUtils.capitalizeFully("")          = ""
+     * WordUtils.capitalizeFully("i am FINE") = "I Am Fine"
+     * 
+ * + * @param str the String to capitalize, may be null + * @return capitalized String, null if null String input + */ + public static String capitalizeFully(final String str) { + return capitalizeFully(str, null); + } + + /** + *

Converts all the delimiter separated words in a String into capitalized words, + * that is each word is made up of a titlecase character and then a series of + * lowercase characters.

+ * + *

The delimiters represent a set of characters understood to separate words. + * The first string character and the first non-delimiter character after a + * delimiter will be capitalized.

+ * + *

A null input String returns null. + * Capitalization uses the Unicode title case, normally equivalent to + * upper case.

+ * + *
+     * WordUtils.capitalizeFully(null, *)            = null
+     * WordUtils.capitalizeFully("", *)              = ""
+     * WordUtils.capitalizeFully(*, null)            = *
+     * WordUtils.capitalizeFully(*, new char[0])     = *
+     * WordUtils.capitalizeFully("i aM.fine", {'.'}) = "I am.Fine"
+     * 
+ * + * @param str the String to capitalize, may be null + * @param delimiters set of characters to determine capitalization, null means whitespace + * @return capitalized String, null if null String input + * @since 2.1 + */ + public static String capitalizeFully(String str, final char... delimiters) { + final int delimLen = delimiters == null ? -1 : delimiters.length; + if (StringUtils.isEmpty(str) || delimLen == 0) { + return str; + } + str = str.toLowerCase(); + return capitalize(str, delimiters); + } + + //----------------------------------------------------------------------- + /** + *

Uncapitalizes all the whitespace separated words in a String. + * Only the first character of each word is changed.

+ * + *

Whitespace is defined by {@link Character#isWhitespace(char)}. + * A null input String returns null.

+ * + *
+     * WordUtils.uncapitalize(null)        = null
+     * WordUtils.uncapitalize("")          = ""
+     * WordUtils.uncapitalize("I Am FINE") = "i am fINE"
+     * 
+ * + * @param str the String to uncapitalize, may be null + * @return uncapitalized String, null if null String input + * @see #capitalize(String) + */ + public static String uncapitalize(final String str) { + return uncapitalize(str, null); + } + + /** + *

Uncapitalizes all the whitespace separated words in a String. + * Only the first character of each word is changed.

+ * + *

The delimiters represent a set of characters understood to separate words. + * The first string character and the first non-delimiter character after a + * delimiter will be uncapitalized.

+ * + *

Whitespace is defined by {@link Character#isWhitespace(char)}. + * A null input String returns null.

+ * + *
+     * WordUtils.uncapitalize(null, *)            = null
+     * WordUtils.uncapitalize("", *)              = ""
+     * WordUtils.uncapitalize(*, null)            = *
+     * WordUtils.uncapitalize(*, new char[0])     = *
+     * WordUtils.uncapitalize("I AM.FINE", {'.'}) = "i AM.fINE"
+     * 
+ * + * @param str the String to uncapitalize, may be null + * @param delimiters set of characters to determine uncapitalization, null means whitespace + * @return uncapitalized String, null if null String input + * @see #capitalize(String) + * @since 2.1 + */ + public static String uncapitalize(final String str, final char... delimiters) { + final int delimLen = delimiters == null ? -1 : delimiters.length; + if (StringUtils.isEmpty(str) || delimLen == 0) { + return str; + } + final char[] buffer = str.toCharArray(); + boolean uncapitalizeNext = true; + for (int i = 0; i < buffer.length; i++) { + final char ch = buffer[i]; + if (isDelimiter(ch, delimiters)) { + uncapitalizeNext = true; + } else if (uncapitalizeNext) { + buffer[i] = Character.toLowerCase(ch); + uncapitalizeNext = false; + } + } + return new String(buffer); + } + + //----------------------------------------------------------------------- + /** + *

Swaps the case of a String using a word based algorithm.

+ * + * + * + *

Whitespace is defined by {@link Character#isWhitespace(char)}. + * A null input String returns null.

+ * + *
+     * StringUtils.swapCase(null)                 = null
+     * StringUtils.swapCase("")                   = ""
+     * StringUtils.swapCase("The dog has a BONE") = "tHE DOG HAS A bone"
+     * 
+ * + * @param str the String to swap case, may be null + * @return the changed String, null if null String input + */ + public static String swapCase(final String str) { + if (StringUtils.isEmpty(str)) { + return str; + } + final char[] buffer = str.toCharArray(); + + boolean whitespace = true; + + for (int i = 0; i < buffer.length; i++) { + final char ch = buffer[i]; + if (Character.isUpperCase(ch)) { + buffer[i] = Character.toLowerCase(ch); + whitespace = false; + } else if (Character.isTitleCase(ch)) { + buffer[i] = Character.toLowerCase(ch); + whitespace = false; + } else if (Character.isLowerCase(ch)) { + if (whitespace) { + buffer[i] = Character.toTitleCase(ch); + whitespace = false; + } else { + buffer[i] = Character.toUpperCase(ch); + } + } else { + whitespace = Character.isWhitespace(ch); + } + } + return new String(buffer); + } + + //----------------------------------------------------------------------- + /** + *

Extracts the initial characters from each word in the String.

+ * + *

All first characters after whitespace are returned as a new string. + * Their case is not changed.

+ * + *

Whitespace is defined by {@link Character#isWhitespace(char)}. + * A null input String returns null.

+ * + *
+     * WordUtils.initials(null)             = null
+     * WordUtils.initials("")               = ""
+     * WordUtils.initials("Ben John Lee")   = "BJL"
+     * WordUtils.initials("Ben J.Lee")      = "BJ"
+     * 
+ * + * @param str the String to get initials from, may be null + * @return String of initial letters, null if null String input + * @see #initials(String,char[]) + * @since 2.2 + */ + public static String initials(final String str) { + return initials(str, null); + } + + /** + *

Extracts the initial characters from each word in the String.

+ * + *

All first characters after the defined delimiters are returned as a new string. + * Their case is not changed.

+ * + *

If the delimiters array is null, then Whitespace is used. + * Whitespace is defined by {@link Character#isWhitespace(char)}. + * A null input String returns null. + * An empty delimiter array returns an empty String.

+ * + *
+     * WordUtils.initials(null, *)                = null
+     * WordUtils.initials("", *)                  = ""
+     * WordUtils.initials("Ben John Lee", null)   = "BJL"
+     * WordUtils.initials("Ben J.Lee", null)      = "BJ"
+     * WordUtils.initials("Ben J.Lee", [' ','.']) = "BJL"
+     * WordUtils.initials(*, new char[0])         = ""
+     * 
+ * + * @param str the String to get initials from, may be null + * @param delimiters set of characters to determine words, null means whitespace + * @return String of initial characters, null if null String input + * @see #initials(String) + * @since 2.2 + */ + public static String initials(final String str, final char... delimiters) { + if (StringUtils.isEmpty(str)) { + return str; + } + if (delimiters != null && delimiters.length == 0) { + return StringUtils.EMPTY; + } + final int strLen = str.length(); + final char[] buf = new char[strLen / 2 + 1]; + int count = 0; + boolean lastWasGap = true; + for (int i = 0; i < strLen; i++) { + final char ch = str.charAt(i); + + if (isDelimiter(ch, delimiters)) { + lastWasGap = true; + } else if (lastWasGap) { + buf[count++] = ch; + lastWasGap = false; + } else { + continue; // ignore ch + } + } + return new String(buf, 0, count); + } + + //----------------------------------------------------------------------- + /** + *

Checks if the String contains all words in the given array.

+ * + *

+ * A {@code null} String will return {@code false}. A {@code null}, zero + * length search array or if one element of array is null will return {@code false}. + *

+ * + *
+     * WordUtils.containsAllWords(null, *)            = false
+     * WordUtils.containsAllWords("", *)              = false
+     * WordUtils.containsAllWords(*, null)            = false
+     * WordUtils.containsAllWords(*, [])              = false
+     * WordUtils.containsAllWords("abcd", "ab", "cd") = false
+     * WordUtils.containsAllWords("abc def", "def", "abc") = true
+     * 
+ * + * + * @param word The CharSequence to check, may be null + * @param words The array of String words to search for, may be null + * @return {@code true} if all search words are found, {@code false} otherwise + * @since 3.5 + */ + public static boolean containsAllWords(CharSequence word, CharSequence... words) { + if (StringUtils.isEmpty(word) || ArrayUtils.isEmpty(words)) { + return false; + } + for (CharSequence w : words) { + if (StringUtils.isBlank(w)) { + return false; + } + Pattern p = Pattern.compile(".*\\b" + w + "\\b.*"); + if (!p.matcher(word).matches()) { + return false; + } + } + return true; + } + + //----------------------------------------------------------------------- + /** + * Is the character a delimiter. + * + * @param ch the character to check + * @param delimiters the delimiters + * @return true if it is a delimiter + */ + private static boolean isDelimiter(final char ch, final char[] delimiters) { + if (delimiters == null) { + return Character.isWhitespace(ch); + } + for (final char delimiter : delimiters) { + if (ch == delimiter) { + return true; + } + } + return false; + } + +} diff --git a/Java/commons-lang-WordUtils_269/metadata.json b/Java/commons-lang-WordUtils_269/metadata.json new file mode 100644 index 000000000..32cbb752a --- /dev/null +++ b/Java/commons-lang-WordUtils_269/metadata.json @@ -0,0 +1,21 @@ +{ + "language": "java", + "id": "commons-lang-WordUtils_269", + "buggyPath": ".", + "referencePath": null, + "buildCommand": "mvn package -V -B -Denforcer.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true -Drat.skip=true -Dlicense.skip=true -Dfindbugs.skip=true -Dgpg.skip=true -Dskip.npm=true -Dskip.gulp=true -Dskip.bower=true -Drat.numUnapprovedLicenses=100 -DskipTests=true -DskipITs=true -Dtest=None -DfailIfNoTests=false", + "testCommand": "mvn test -V -B -Denforcer.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true -Drat.skip=true -Dlicense.skip=true -Dfindbugs.skip=true -Dgpg.skip=true -Dskip.npm=true -Dskip.gulp=true -Dskip.bower=true -Drat.numUnapprovedLicenses=100", + "categories": [ + "safety", + "npe" + ], + "npe": { + "filepath": "src/main/java/org/apache/commons/lang3/text/WordUtils.java", + "line": 376, + "npe_method": "wrap", + "deref_field": "str", + "npe_class": "WordUtils", + "repo": "commons-lang", + "bug_id": "WordUtils_269" + } +} diff --git a/Java/commons-lang-WordUtils_269/npe.json b/Java/commons-lang-WordUtils_269/npe.json new file mode 100644 index 000000000..3c99681c9 --- /dev/null +++ b/Java/commons-lang-WordUtils_269/npe.json @@ -0,0 +1,7 @@ +{ + "filepath": "src/main/java/org/apache/commons/lang3/text/WordUtils.java", + "line": 376, + "npe_method": "wrap", + "deref_field": "str", + "npe_class": "WordUtils" +} \ No newline at end of file diff --git a/Java/commons-lang-WordUtils_403/Dockerfile b/Java/commons-lang-WordUtils_403/Dockerfile new file mode 100644 index 000000000..7b7fbe349 --- /dev/null +++ b/Java/commons-lang-WordUtils_403/Dockerfile @@ -0,0 +1,18 @@ +FROM ghcr.io/kupl/starlab-benchmarks/java-base:commons-lang + +ENV TZ=Asia/Seoul + +COPY ./metadata.json . +COPY ./npe.json . +COPY ./buggy.java /tmp/buggy.java +RUN export BUGGY_PATH=$(cat metadata.json | jq -r ".npe.filepath") \ + && export BUGGY_LINE=$(cat metadata.json | jq -r ".npe.line") \ + && export BUGGY_MTHD=$(cat metadata.json | jq -r ".npe.npe_method") \ + && mv /tmp/buggy.java $BUGGY_PATH \ + && echo "[{\"filepath\": \"$BUGGY_PATH\", \"line\": $BUGGY_LINE, \"method_name\": \"$BUGGY_MTHD\"}]" | jq . > traces.json + +RUN git init . && git add -A + +RUN $(cat metadata.json | jq -r ".buildCommand") + +RUN $(cat metadata.json | jq -r ".testCommand"); if [ $? -eq 0 ]; then exit 1; fi diff --git a/Java/commons-lang-WordUtils_403/buggy.java b/Java/commons-lang-WordUtils_403/buggy.java new file mode 100644 index 000000000..639a20aeb --- /dev/null +++ b/Java/commons-lang-WordUtils_403/buggy.java @@ -0,0 +1,769 @@ +/* + * 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.text; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.apache.commons.lang3.ArrayUtils; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.SystemUtils; + +/** + *

Operations on Strings that contain words.

+ * + *

This class tries to handle null input gracefully. + * An exception will not be thrown for a null input. + * Each method documents its behaviour in more detail.

+ * + * @since 2.0 + */ +public class WordUtils { + + /** + *

WordUtils instances should NOT be constructed in + * standard programming. Instead, the class should be used as + * WordUtils.wrap("foo bar", 20);.

+ * + *

This constructor is public to permit tools that require a JavaBean + * instance to operate.

+ */ + public WordUtils() { + super(); + } + + // Wrapping + //-------------------------------------------------------------------------- + /** + *

Wraps a single line of text, identifying words by ' '.

+ * + *

New lines will be separated by the system property line separator. + * Very long words, such as URLs will not be wrapped.

+ * + *

Leading spaces on a new line are stripped. + * Trailing spaces are not stripped.

+ * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
inputwrapLengthresult
null*null
""*""
"Here is one line of text that is going to be wrapped after 20 columns."20"Here is one line of\ntext that is going\nto be wrapped after\n20 columns."
"Click here to jump to the commons website - http://commons.apache.org"20"Click here to jump\nto the commons\nwebsite -\nhttp://commons.apache.org"
"Click here, http://commons.apache.org, to jump to the commons website"20"Click here,\nhttp://commons.apache.org,\nto jump to the\ncommons website"
+ * + * (assuming that '\n' is the systems line separator) + * + * @param str the String to be word wrapped, may be null + * @param wrapLength the column to wrap the words at, less than 1 is treated as 1 + * @return a line with newlines inserted, null if null input + */ + public static String wrap(final String str, final int wrapLength) { + return wrap(str, wrapLength, null, false); + } + + /** + *

Wraps a single line of text, identifying words by ' '.

+ * + *

Leading spaces on a new line are stripped. + * Trailing spaces are not stripped.

+ * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
inputwrapLenghtnewLineStringwrapLongWordsresult
null**true/falsenull
""**true/false""
"Here is one line of text that is going to be wrapped after 20 columns."20"\n"true/false"Here is one line of\ntext that is going\nto be wrapped after\n20 columns."
"Here is one line of text that is going to be wrapped after 20 columns."20"<br />"true/false"Here is one line of<br />text that is going<br />to be wrapped after<br />20 columns."
"Here is one line of text that is going to be wrapped after 20 columns."20nulltrue/false"Here is one line of" + systemNewLine + "text that is going" + systemNewLine + "to be wrapped after" + systemNewLine + "20 columns."
"Click here to jump to the commons website - http://commons.apache.org"20"\n"false"Click here to jump\nto the commons\nwebsite -\nhttp://commons.apache.org"
"Click here to jump to the commons website - http://commons.apache.org"20"\n"true"Click here to jump\nto the commons\nwebsite -\nhttp://commons.apach\ne.org"
+ * + * @param str the String to be word wrapped, may be null + * @param wrapLength the column to wrap the words at, less than 1 is treated as 1 + * @param newLineStr the string to insert for a new line, + * null uses the system property line separator + * @param wrapLongWords true if long words (such as URLs) should be wrapped + * @return a line with newlines inserted, null if null input + */ + public static String wrap(final String str, int wrapLength, String newLineStr, final boolean wrapLongWords) { + return wrap(str, wrapLength, newLineStr, wrapLongWords, " "); + } + + /** + *

Wraps a single line of text, identifying words by wrapOn.

+ * + *

Leading spaces on a new line are stripped. + * Trailing spaces are not stripped.

+ * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
inputwrapLenghtnewLineStringwrapLongWordswrapOnresult
null**true/false*null
""**true/false*""
"Here is one line of text that is going to be wrapped after 20 columns."20"\n"true/false" ""Here is one line of\ntext that is going\nto be wrapped after\n20 columns."
"Here is one line of text that is going to be wrapped after 20 columns."20"<br />"true/false" ""Here is one line of<br />text that is going<br />to be wrapped after<br />20 columns."
"Here is one line of text that is going to be wrapped after 20 columns."20nulltrue/false" ""Here is one line of" + systemNewLine + "text that is going" + systemNewLine + "to be wrapped after" + systemNewLine + "20 columns."
"Click here to jump to the commons website - http://commons.apache.org"20"\n"false" ""Click here to jump\nto the commons\nwebsite -\nhttp://commons.apache.org"
"Click here to jump to the commons website - http://commons.apache.org"20"\n"true" ""Click here to jump\nto the commons\nwebsite -\nhttp://commons.apach\ne.org"
"flammable/inflammable"20"\n"true"/""flammable\ninflammable"
+ * @param str the String to be word wrapped, may be null + * @param wrapLength the column to wrap the words at, less than 1 is treated as 1 + * @param newLineStr the string to insert for a new line, + * null uses the system property line separator + * @param wrapLongWords true if long words (such as URLs) should be wrapped + * @param wrapOn regex expression to be used as a breakable characters, + * if blank string is provided a space character will be used + * @return a line with newlines inserted, null if null input + */ + public static String wrap(final String str, int wrapLength, String newLineStr, final boolean wrapLongWords, String wrapOn) { + if (str == null) { + return null; + } + if (newLineStr == null) { + newLineStr = SystemUtils.LINE_SEPARATOR; + } + if (wrapLength < 1) { + wrapLength = 1; + } + if (StringUtils.isBlank(wrapOn)) { + wrapOn = " "; + } + Pattern patternToWrapOn = Pattern.compile(wrapOn); + final int inputLineLength = str.length(); + int offset = 0; + final StringBuilder wrappedLine = new StringBuilder(inputLineLength + 32); + + while (offset < inputLineLength) { + int spaceToWrapAt = -1; + Matcher matcher = patternToWrapOn.matcher(str.substring(offset, Math.min(offset + wrapLength + 1, inputLineLength))); + if (matcher.find()) { + if (matcher.start() == 0) { + offset += matcher.end(); + continue; + }else { + spaceToWrapAt = matcher.start(); + } + } + + // only last line without leading spaces is left + if(inputLineLength - offset <= wrapLength) { + break; + } + + while(matcher.find()){ + spaceToWrapAt = matcher.start() + offset; + } + + if (spaceToWrapAt >= offset) { + // normal case + wrappedLine.append(str.substring(offset, spaceToWrapAt)); + wrappedLine.append(newLineStr); + offset = spaceToWrapAt + 1; + + } else { + // really long word or URL + if (wrapLongWords) { + // wrap really long word one line at a time + wrappedLine.append(str.substring(offset, wrapLength + offset)); + wrappedLine.append(newLineStr); + offset += wrapLength; + } else { + // do not wrap really long word, just extend beyond limit + matcher = patternToWrapOn.matcher(str.substring(offset + wrapLength)); + if (matcher.find()) { + spaceToWrapAt = matcher.start() + offset + wrapLength; + } + + if (spaceToWrapAt >= 0) { + wrappedLine.append(str.substring(offset, spaceToWrapAt)); + wrappedLine.append(newLineStr); + offset = spaceToWrapAt + 1; + } else { + wrappedLine.append(str.substring(offset)); + offset = inputLineLength; + } + } + } + } + + // Whatever is left in line is short enough to just pass through + wrappedLine.append(str.substring(offset)); + + return wrappedLine.toString(); + } + + // Capitalizing + //----------------------------------------------------------------------- + /** + *

Capitalizes all the whitespace separated words in a String. + * Only the first character of each word is changed. To convert the + * rest of each word to lowercase at the same time, + * use {@link #capitalizeFully(String)}.

+ * + *

Whitespace is defined by {@link Character#isWhitespace(char)}. + * A null input String returns null. + * Capitalization uses the Unicode title case, normally equivalent to + * upper case.

+ * + *
+     * WordUtils.capitalize(null)        = null
+     * WordUtils.capitalize("")          = ""
+     * WordUtils.capitalize("i am FINE") = "I Am FINE"
+     * 
+ * + * @param str the String to capitalize, may be null + * @return capitalized String, null if null String input + * @see #uncapitalize(String) + * @see #capitalizeFully(String) + */ + public static String capitalize(final String str) { + return capitalize(str, null); + } + + /** + *

Capitalizes all the delimiter separated words in a String. + * Only the first character of each word is changed. To convert the + * rest of each word to lowercase at the same time, + * use {@link #capitalizeFully(String, char[])}.

+ * + *

The delimiters represent a set of characters understood to separate words. + * The first string character and the first non-delimiter character after a + * delimiter will be capitalized.

+ * + *

A null input String returns null. + * Capitalization uses the Unicode title case, normally equivalent to + * upper case.

+ * + *
+     * WordUtils.capitalize(null, *)            = null
+     * WordUtils.capitalize("", *)              = ""
+     * WordUtils.capitalize(*, new char[0])     = *
+     * WordUtils.capitalize("i am fine", null)  = "I Am Fine"
+     * WordUtils.capitalize("i aM.fine", {'.'}) = "I aM.Fine"
+     * 
+ * + * @param str the String to capitalize, may be null + * @param delimiters set of characters to determine capitalization, null means whitespace + * @return capitalized String, null if null String input + * @see #uncapitalize(String) + * @see #capitalizeFully(String) + * @since 2.1 + */ +/** + *

Capitalizes all the delimiter separated words in a String. + * Only the first character of each word is changed. To convert the + * rest of each word to lowercase at the same time, + * use {@link #capitalizeFully(String, char[])}.

+ * + *

The delimiters represent a set of characters understood to separate words. + * The first string character and the first non-delimiter character after a + * delimiter will be capitalized.

+ * + *

A null input String returns null. + * Capitalization uses the Unicode title case, normally equivalent to + * upper case.

+ * + *
+ * WordUtils.capitalize(null, *)            = null
+ * WordUtils.capitalize("", *)              = ""
+ * WordUtils.capitalize(*, new char[0])     = *
+ * WordUtils.capitalize("i am fine", null)  = "I Am Fine"
+ * WordUtils.capitalize("i aM.fine", {'.'}) = "I aM.Fine"
+ * 
+ * + * @param str + * the String to capitalize, may be null + * @param delimiters + * set of characters to determine capitalization, null means whitespace + * @return capitalized String, null if null String input + * @see #uncapitalize(String) + * @see #capitalizeFully(String) + * @since 2.1 + */ +public static java.lang.String capitalize(final java.lang.String str, final char... delimiters) { + final int delimLen = /* NPEX_NULL_EXP */ + delimiters.length; + if (org.apache.commons.lang3.StringUtils.isEmpty(str) || (delimLen == 0)) { + return str; + } + final char[] buffer = str.toCharArray(); + boolean capitalizeNext = true; + for (int i = 0; i < buffer.length; i++) { + final char ch = buffer[i]; + if (org.apache.commons.lang3.text.WordUtils.isDelimiter(ch, delimiters)) { + capitalizeNext = true; + } else if (capitalizeNext) { + buffer[i] = java.lang.Character.toTitleCase(ch); + capitalizeNext = false; + } + } + return new java.lang.String(buffer); +} + + //----------------------------------------------------------------------- + /** + *

Converts all the whitespace separated words in a String into capitalized words, + * that is each word is made up of a titlecase character and then a series of + * lowercase characters.

+ * + *

Whitespace is defined by {@link Character#isWhitespace(char)}. + * A null input String returns null. + * Capitalization uses the Unicode title case, normally equivalent to + * upper case.

+ * + *
+     * WordUtils.capitalizeFully(null)        = null
+     * WordUtils.capitalizeFully("")          = ""
+     * WordUtils.capitalizeFully("i am FINE") = "I Am Fine"
+     * 
+ * + * @param str the String to capitalize, may be null + * @return capitalized String, null if null String input + */ + public static String capitalizeFully(final String str) { + return capitalizeFully(str, null); + } + + /** + *

Converts all the delimiter separated words in a String into capitalized words, + * that is each word is made up of a titlecase character and then a series of + * lowercase characters.

+ * + *

The delimiters represent a set of characters understood to separate words. + * The first string character and the first non-delimiter character after a + * delimiter will be capitalized.

+ * + *

A null input String returns null. + * Capitalization uses the Unicode title case, normally equivalent to + * upper case.

+ * + *
+     * WordUtils.capitalizeFully(null, *)            = null
+     * WordUtils.capitalizeFully("", *)              = ""
+     * WordUtils.capitalizeFully(*, null)            = *
+     * WordUtils.capitalizeFully(*, new char[0])     = *
+     * WordUtils.capitalizeFully("i aM.fine", {'.'}) = "I am.Fine"
+     * 
+ * + * @param str the String to capitalize, may be null + * @param delimiters set of characters to determine capitalization, null means whitespace + * @return capitalized String, null if null String input + * @since 2.1 + */ + public static String capitalizeFully(String str, final char... delimiters) { + final int delimLen = delimiters == null ? -1 : delimiters.length; + if (StringUtils.isEmpty(str) || delimLen == 0) { + return str; + } + str = str.toLowerCase(); + return capitalize(str, delimiters); + } + + //----------------------------------------------------------------------- + /** + *

Uncapitalizes all the whitespace separated words in a String. + * Only the first character of each word is changed.

+ * + *

Whitespace is defined by {@link Character#isWhitespace(char)}. + * A null input String returns null.

+ * + *
+     * WordUtils.uncapitalize(null)        = null
+     * WordUtils.uncapitalize("")          = ""
+     * WordUtils.uncapitalize("I Am FINE") = "i am fINE"
+     * 
+ * + * @param str the String to uncapitalize, may be null + * @return uncapitalized String, null if null String input + * @see #capitalize(String) + */ + public static String uncapitalize(final String str) { + return uncapitalize(str, null); + } + + /** + *

Uncapitalizes all the whitespace separated words in a String. + * Only the first character of each word is changed.

+ * + *

The delimiters represent a set of characters understood to separate words. + * The first string character and the first non-delimiter character after a + * delimiter will be uncapitalized.

+ * + *

Whitespace is defined by {@link Character#isWhitespace(char)}. + * A null input String returns null.

+ * + *
+     * WordUtils.uncapitalize(null, *)            = null
+     * WordUtils.uncapitalize("", *)              = ""
+     * WordUtils.uncapitalize(*, null)            = *
+     * WordUtils.uncapitalize(*, new char[0])     = *
+     * WordUtils.uncapitalize("I AM.FINE", {'.'}) = "i AM.fINE"
+     * 
+ * + * @param str the String to uncapitalize, may be null + * @param delimiters set of characters to determine uncapitalization, null means whitespace + * @return uncapitalized String, null if null String input + * @see #capitalize(String) + * @since 2.1 + */ + public static String uncapitalize(final String str, final char... delimiters) { + final int delimLen = delimiters == null ? -1 : delimiters.length; + if (StringUtils.isEmpty(str) || delimLen == 0) { + return str; + } + final char[] buffer = str.toCharArray(); + boolean uncapitalizeNext = true; + for (int i = 0; i < buffer.length; i++) { + final char ch = buffer[i]; + if (isDelimiter(ch, delimiters)) { + uncapitalizeNext = true; + } else if (uncapitalizeNext) { + buffer[i] = Character.toLowerCase(ch); + uncapitalizeNext = false; + } + } + return new String(buffer); + } + + //----------------------------------------------------------------------- + /** + *

Swaps the case of a String using a word based algorithm.

+ * + * + * + *

Whitespace is defined by {@link Character#isWhitespace(char)}. + * A null input String returns null.

+ * + *
+     * StringUtils.swapCase(null)                 = null
+     * StringUtils.swapCase("")                   = ""
+     * StringUtils.swapCase("The dog has a BONE") = "tHE DOG HAS A bone"
+     * 
+ * + * @param str the String to swap case, may be null + * @return the changed String, null if null String input + */ + public static String swapCase(final String str) { + if (StringUtils.isEmpty(str)) { + return str; + } + final char[] buffer = str.toCharArray(); + + boolean whitespace = true; + + for (int i = 0; i < buffer.length; i++) { + final char ch = buffer[i]; + if (Character.isUpperCase(ch)) { + buffer[i] = Character.toLowerCase(ch); + whitespace = false; + } else if (Character.isTitleCase(ch)) { + buffer[i] = Character.toLowerCase(ch); + whitespace = false; + } else if (Character.isLowerCase(ch)) { + if (whitespace) { + buffer[i] = Character.toTitleCase(ch); + whitespace = false; + } else { + buffer[i] = Character.toUpperCase(ch); + } + } else { + whitespace = Character.isWhitespace(ch); + } + } + return new String(buffer); + } + + //----------------------------------------------------------------------- + /** + *

Extracts the initial characters from each word in the String.

+ * + *

All first characters after whitespace are returned as a new string. + * Their case is not changed.

+ * + *

Whitespace is defined by {@link Character#isWhitespace(char)}. + * A null input String returns null.

+ * + *
+     * WordUtils.initials(null)             = null
+     * WordUtils.initials("")               = ""
+     * WordUtils.initials("Ben John Lee")   = "BJL"
+     * WordUtils.initials("Ben J.Lee")      = "BJ"
+     * 
+ * + * @param str the String to get initials from, may be null + * @return String of initial letters, null if null String input + * @see #initials(String,char[]) + * @since 2.2 + */ + public static String initials(final String str) { + return initials(str, null); + } + + /** + *

Extracts the initial characters from each word in the String.

+ * + *

All first characters after the defined delimiters are returned as a new string. + * Their case is not changed.

+ * + *

If the delimiters array is null, then Whitespace is used. + * Whitespace is defined by {@link Character#isWhitespace(char)}. + * A null input String returns null. + * An empty delimiter array returns an empty String.

+ * + *
+     * WordUtils.initials(null, *)                = null
+     * WordUtils.initials("", *)                  = ""
+     * WordUtils.initials("Ben John Lee", null)   = "BJL"
+     * WordUtils.initials("Ben J.Lee", null)      = "BJ"
+     * WordUtils.initials("Ben J.Lee", [' ','.']) = "BJL"
+     * WordUtils.initials(*, new char[0])         = ""
+     * 
+ * + * @param str the String to get initials from, may be null + * @param delimiters set of characters to determine words, null means whitespace + * @return String of initial characters, null if null String input + * @see #initials(String) + * @since 2.2 + */ + public static String initials(final String str, final char... delimiters) { + if (StringUtils.isEmpty(str)) { + return str; + } + if (delimiters != null && delimiters.length == 0) { + return StringUtils.EMPTY; + } + final int strLen = str.length(); + final char[] buf = new char[strLen / 2 + 1]; + int count = 0; + boolean lastWasGap = true; + for (int i = 0; i < strLen; i++) { + final char ch = str.charAt(i); + + if (isDelimiter(ch, delimiters)) { + lastWasGap = true; + } else if (lastWasGap) { + buf[count++] = ch; + lastWasGap = false; + } else { + continue; // ignore ch + } + } + return new String(buf, 0, count); + } + + //----------------------------------------------------------------------- + /** + *

Checks if the String contains all words in the given array.

+ * + *

+ * A {@code null} String will return {@code false}. A {@code null}, zero + * length search array or if one element of array is null will return {@code false}. + *

+ * + *
+     * WordUtils.containsAllWords(null, *)            = false
+     * WordUtils.containsAllWords("", *)              = false
+     * WordUtils.containsAllWords(*, null)            = false
+     * WordUtils.containsAllWords(*, [])              = false
+     * WordUtils.containsAllWords("abcd", "ab", "cd") = false
+     * WordUtils.containsAllWords("abc def", "def", "abc") = true
+     * 
+ * + * + * @param word The CharSequence to check, may be null + * @param words The array of String words to search for, may be null + * @return {@code true} if all search words are found, {@code false} otherwise + * @since 3.5 + */ + public static boolean containsAllWords(CharSequence word, CharSequence... words) { + if (StringUtils.isEmpty(word) || ArrayUtils.isEmpty(words)) { + return false; + } + for (CharSequence w : words) { + if (StringUtils.isBlank(w)) { + return false; + } + Pattern p = Pattern.compile(".*\\b" + w + "\\b.*"); + if (!p.matcher(word).matches()) { + return false; + } + } + return true; + } + + //----------------------------------------------------------------------- + /** + * Is the character a delimiter. + * + * @param ch the character to check + * @param delimiters the delimiters + * @return true if it is a delimiter + */ + private static boolean isDelimiter(final char ch, final char[] delimiters) { + if (delimiters == null) { + return Character.isWhitespace(ch); + } + for (final char delimiter : delimiters) { + if (ch == delimiter) { + return true; + } + } + return false; + } + +} diff --git a/Java/commons-lang-WordUtils_403/metadata.json b/Java/commons-lang-WordUtils_403/metadata.json new file mode 100644 index 000000000..079822e19 --- /dev/null +++ b/Java/commons-lang-WordUtils_403/metadata.json @@ -0,0 +1,21 @@ +{ + "language": "java", + "id": "commons-lang-WordUtils_403", + "buggyPath": ".", + "referencePath": null, + "buildCommand": "mvn package -V -B -Denforcer.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true -Drat.skip=true -Dlicense.skip=true -Dfindbugs.skip=true -Dgpg.skip=true -Dskip.npm=true -Dskip.gulp=true -Dskip.bower=true -Drat.numUnapprovedLicenses=100 -DskipTests=true -DskipITs=true -Dtest=None -DfailIfNoTests=false", + "testCommand": "mvn test -V -B -Denforcer.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true -Drat.skip=true -Dlicense.skip=true -Dfindbugs.skip=true -Dgpg.skip=true -Dskip.npm=true -Dskip.gulp=true -Dskip.bower=true -Drat.numUnapprovedLicenses=100", + "categories": [ + "safety", + "npe" + ], + "npe": { + "filepath": "src/main/java/org/apache/commons/lang3/text/WordUtils.java", + "line": 435, + "npe_method": "capitalize", + "deref_field": "delimiters", + "npe_class": "WordUtils", + "repo": "commons-lang", + "bug_id": "WordUtils_403" + } +} diff --git a/Java/commons-lang-WordUtils_403/npe.json b/Java/commons-lang-WordUtils_403/npe.json new file mode 100644 index 000000000..523b7d95d --- /dev/null +++ b/Java/commons-lang-WordUtils_403/npe.json @@ -0,0 +1,7 @@ +{ + "filepath": "src/main/java/org/apache/commons/lang3/text/WordUtils.java", + "line": 435, + "npe_method": "capitalize", + "deref_field": "delimiters", + "npe_class": "WordUtils" +} \ No newline at end of file diff --git a/Java/commons-lang-WordUtils_726/Dockerfile b/Java/commons-lang-WordUtils_726/Dockerfile new file mode 100644 index 000000000..7b7fbe349 --- /dev/null +++ b/Java/commons-lang-WordUtils_726/Dockerfile @@ -0,0 +1,18 @@ +FROM ghcr.io/kupl/starlab-benchmarks/java-base:commons-lang + +ENV TZ=Asia/Seoul + +COPY ./metadata.json . +COPY ./npe.json . +COPY ./buggy.java /tmp/buggy.java +RUN export BUGGY_PATH=$(cat metadata.json | jq -r ".npe.filepath") \ + && export BUGGY_LINE=$(cat metadata.json | jq -r ".npe.line") \ + && export BUGGY_MTHD=$(cat metadata.json | jq -r ".npe.npe_method") \ + && mv /tmp/buggy.java $BUGGY_PATH \ + && echo "[{\"filepath\": \"$BUGGY_PATH\", \"line\": $BUGGY_LINE, \"method_name\": \"$BUGGY_MTHD\"}]" | jq . > traces.json + +RUN git init . && git add -A + +RUN $(cat metadata.json | jq -r ".buildCommand") + +RUN $(cat metadata.json | jq -r ".testCommand"); if [ $? -eq 0 ]; then exit 1; fi diff --git a/Java/commons-lang-WordUtils_726/buggy.java b/Java/commons-lang-WordUtils_726/buggy.java new file mode 100644 index 000000000..48aef8624 --- /dev/null +++ b/Java/commons-lang-WordUtils_726/buggy.java @@ -0,0 +1,747 @@ +/* + * 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.text; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.apache.commons.lang3.ArrayUtils; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.SystemUtils; + +/** + *

Operations on Strings that contain words.

+ * + *

This class tries to handle null input gracefully. + * An exception will not be thrown for a null input. + * Each method documents its behaviour in more detail.

+ * + * @since 2.0 + */ +public class WordUtils { + + /** + *

WordUtils instances should NOT be constructed in + * standard programming. Instead, the class should be used as + * WordUtils.wrap("foo bar", 20);.

+ * + *

This constructor is public to permit tools that require a JavaBean + * instance to operate.

+ */ + public WordUtils() { + super(); + } + + // Wrapping + //-------------------------------------------------------------------------- + /** + *

Wraps a single line of text, identifying words by ' '.

+ * + *

New lines will be separated by the system property line separator. + * Very long words, such as URLs will not be wrapped.

+ * + *

Leading spaces on a new line are stripped. + * Trailing spaces are not stripped.

+ * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
inputwrapLengthresult
null*null
""*""
"Here is one line of text that is going to be wrapped after 20 columns."20"Here is one line of\ntext that is going\nto be wrapped after\n20 columns."
"Click here to jump to the commons website - http://commons.apache.org"20"Click here to jump\nto the commons\nwebsite -\nhttp://commons.apache.org"
"Click here, http://commons.apache.org, to jump to the commons website"20"Click here,\nhttp://commons.apache.org,\nto jump to the\ncommons website"
+ * + * (assuming that '\n' is the systems line separator) + * + * @param str the String to be word wrapped, may be null + * @param wrapLength the column to wrap the words at, less than 1 is treated as 1 + * @return a line with newlines inserted, null if null input + */ + public static String wrap(final String str, final int wrapLength) { + return wrap(str, wrapLength, null, false); + } + + /** + *

Wraps a single line of text, identifying words by ' '.

+ * + *

Leading spaces on a new line are stripped. + * Trailing spaces are not stripped.

+ * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
inputwrapLenghtnewLineStringwrapLongWordsresult
null**true/falsenull
""**true/false""
"Here is one line of text that is going to be wrapped after 20 columns."20"\n"true/false"Here is one line of\ntext that is going\nto be wrapped after\n20 columns."
"Here is one line of text that is going to be wrapped after 20 columns."20"<br />"true/false"Here is one line of<br />text that is going<br />to be wrapped after<br />20 columns."
"Here is one line of text that is going to be wrapped after 20 columns."20nulltrue/false"Here is one line of" + systemNewLine + "text that is going" + systemNewLine + "to be wrapped after" + systemNewLine + "20 columns."
"Click here to jump to the commons website - http://commons.apache.org"20"\n"false"Click here to jump\nto the commons\nwebsite -\nhttp://commons.apache.org"
"Click here to jump to the commons website - http://commons.apache.org"20"\n"true"Click here to jump\nto the commons\nwebsite -\nhttp://commons.apach\ne.org"
+ * + * @param str the String to be word wrapped, may be null + * @param wrapLength the column to wrap the words at, less than 1 is treated as 1 + * @param newLineStr the string to insert for a new line, + * null uses the system property line separator + * @param wrapLongWords true if long words (such as URLs) should be wrapped + * @return a line with newlines inserted, null if null input + */ + public static String wrap(final String str, int wrapLength, String newLineStr, final boolean wrapLongWords) { + return wrap(str, wrapLength, newLineStr, wrapLongWords, " "); + } + + /** + *

Wraps a single line of text, identifying words by wrapOn.

+ * + *

Leading spaces on a new line are stripped. + * Trailing spaces are not stripped.

+ * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
inputwrapLenghtnewLineStringwrapLongWordswrapOnresult
null**true/false*null
""**true/false*""
"Here is one line of text that is going to be wrapped after 20 columns."20"\n"true/false" ""Here is one line of\ntext that is going\nto be wrapped after\n20 columns."
"Here is one line of text that is going to be wrapped after 20 columns."20"<br />"true/false" ""Here is one line of<br />text that is going<br />to be wrapped after<br />20 columns."
"Here is one line of text that is going to be wrapped after 20 columns."20nulltrue/false" ""Here is one line of" + systemNewLine + "text that is going" + systemNewLine + "to be wrapped after" + systemNewLine + "20 columns."
"Click here to jump to the commons website - http://commons.apache.org"20"\n"false" ""Click here to jump\nto the commons\nwebsite -\nhttp://commons.apache.org"
"Click here to jump to the commons website - http://commons.apache.org"20"\n"true" ""Click here to jump\nto the commons\nwebsite -\nhttp://commons.apach\ne.org"
"flammable/inflammable"20"\n"true"/""flammable\ninflammable"
+ * @param str the String to be word wrapped, may be null + * @param wrapLength the column to wrap the words at, less than 1 is treated as 1 + * @param newLineStr the string to insert for a new line, + * null uses the system property line separator + * @param wrapLongWords true if long words (such as URLs) should be wrapped + * @param wrapOn regex expression to be used as a breakable characters, + * if blank string is provided a space character will be used + * @return a line with newlines inserted, null if null input + */ + public static String wrap(final String str, int wrapLength, String newLineStr, final boolean wrapLongWords, String wrapOn) { + if (str == null) { + return null; + } + if (newLineStr == null) { + newLineStr = SystemUtils.LINE_SEPARATOR; + } + if (wrapLength < 1) { + wrapLength = 1; + } + if (StringUtils.isBlank(wrapOn)) { + wrapOn = " "; + } + Pattern patternToWrapOn = Pattern.compile(wrapOn); + final int inputLineLength = str.length(); + int offset = 0; + final StringBuilder wrappedLine = new StringBuilder(inputLineLength + 32); + + while (offset < inputLineLength) { + int spaceToWrapAt = -1; + Matcher matcher = patternToWrapOn.matcher(str.substring(offset, Math.min(offset + wrapLength + 1, inputLineLength))); + if (matcher.find()) { + if (matcher.start() == 0) { + offset += matcher.end(); + continue; + }else { + spaceToWrapAt = matcher.start(); + } + } + + // only last line without leading spaces is left + if(inputLineLength - offset <= wrapLength) { + break; + } + + while(matcher.find()){ + spaceToWrapAt = matcher.start() + offset; + } + + if (spaceToWrapAt >= offset) { + // normal case + wrappedLine.append(str.substring(offset, spaceToWrapAt)); + wrappedLine.append(newLineStr); + offset = spaceToWrapAt + 1; + + } else { + // really long word or URL + if (wrapLongWords) { + // wrap really long word one line at a time + wrappedLine.append(str.substring(offset, wrapLength + offset)); + wrappedLine.append(newLineStr); + offset += wrapLength; + } else { + // do not wrap really long word, just extend beyond limit + matcher = patternToWrapOn.matcher(str.substring(offset + wrapLength)); + if (matcher.find()) { + spaceToWrapAt = matcher.start() + offset + wrapLength; + } + + if (spaceToWrapAt >= 0) { + wrappedLine.append(str.substring(offset, spaceToWrapAt)); + wrappedLine.append(newLineStr); + offset = spaceToWrapAt + 1; + } else { + wrappedLine.append(str.substring(offset)); + offset = inputLineLength; + } + } + } + } + + // Whatever is left in line is short enough to just pass through + wrappedLine.append(str.substring(offset)); + + return wrappedLine.toString(); + } + + // Capitalizing + //----------------------------------------------------------------------- + /** + *

Capitalizes all the whitespace separated words in a String. + * Only the first character of each word is changed. To convert the + * rest of each word to lowercase at the same time, + * use {@link #capitalizeFully(String)}.

+ * + *

Whitespace is defined by {@link Character#isWhitespace(char)}. + * A null input String returns null. + * Capitalization uses the Unicode title case, normally equivalent to + * upper case.

+ * + *
+     * WordUtils.capitalize(null)        = null
+     * WordUtils.capitalize("")          = ""
+     * WordUtils.capitalize("i am FINE") = "I Am FINE"
+     * 
+ * + * @param str the String to capitalize, may be null + * @return capitalized String, null if null String input + * @see #uncapitalize(String) + * @see #capitalizeFully(String) + */ + public static String capitalize(final String str) { + return capitalize(str, null); + } + + /** + *

Capitalizes all the delimiter separated words in a String. + * Only the first character of each word is changed. To convert the + * rest of each word to lowercase at the same time, + * use {@link #capitalizeFully(String, char[])}.

+ * + *

The delimiters represent a set of characters understood to separate words. + * The first string character and the first non-delimiter character after a + * delimiter will be capitalized.

+ * + *

A null input String returns null. + * Capitalization uses the Unicode title case, normally equivalent to + * upper case.

+ * + *
+     * WordUtils.capitalize(null, *)            = null
+     * WordUtils.capitalize("", *)              = ""
+     * WordUtils.capitalize(*, new char[0])     = *
+     * WordUtils.capitalize("i am fine", null)  = "I Am Fine"
+     * WordUtils.capitalize("i aM.fine", {'.'}) = "I aM.Fine"
+     * 
+ * + * @param str the String to capitalize, may be null + * @param delimiters set of characters to determine capitalization, null means whitespace + * @return capitalized String, null if null String input + * @see #uncapitalize(String) + * @see #capitalizeFully(String) + * @since 2.1 + */ + public static String capitalize(final String str, final char... delimiters) { + final int delimLen = delimiters == null ? -1 : delimiters.length; + if (StringUtils.isEmpty(str) || delimLen == 0) { + return str; + } + final char[] buffer = str.toCharArray(); + boolean capitalizeNext = true; + for (int i = 0; i < buffer.length; i++) { + final char ch = buffer[i]; + if (isDelimiter(ch, delimiters)) { + capitalizeNext = true; + } else if (capitalizeNext) { + buffer[i] = Character.toTitleCase(ch); + capitalizeNext = false; + } + } + return new String(buffer); + } + + //----------------------------------------------------------------------- + /** + *

Converts all the whitespace separated words in a String into capitalized words, + * that is each word is made up of a titlecase character and then a series of + * lowercase characters.

+ * + *

Whitespace is defined by {@link Character#isWhitespace(char)}. + * A null input String returns null. + * Capitalization uses the Unicode title case, normally equivalent to + * upper case.

+ * + *
+     * WordUtils.capitalizeFully(null)        = null
+     * WordUtils.capitalizeFully("")          = ""
+     * WordUtils.capitalizeFully("i am FINE") = "I Am Fine"
+     * 
+ * + * @param str the String to capitalize, may be null + * @return capitalized String, null if null String input + */ + public static String capitalizeFully(final String str) { + return capitalizeFully(str, null); + } + + /** + *

Converts all the delimiter separated words in a String into capitalized words, + * that is each word is made up of a titlecase character and then a series of + * lowercase characters.

+ * + *

The delimiters represent a set of characters understood to separate words. + * The first string character and the first non-delimiter character after a + * delimiter will be capitalized.

+ * + *

A null input String returns null. + * Capitalization uses the Unicode title case, normally equivalent to + * upper case.

+ * + *
+     * WordUtils.capitalizeFully(null, *)            = null
+     * WordUtils.capitalizeFully("", *)              = ""
+     * WordUtils.capitalizeFully(*, null)            = *
+     * WordUtils.capitalizeFully(*, new char[0])     = *
+     * WordUtils.capitalizeFully("i aM.fine", {'.'}) = "I am.Fine"
+     * 
+ * + * @param str the String to capitalize, may be null + * @param delimiters set of characters to determine capitalization, null means whitespace + * @return capitalized String, null if null String input + * @since 2.1 + */ + public static String capitalizeFully(String str, final char... delimiters) { + final int delimLen = delimiters == null ? -1 : delimiters.length; + if (StringUtils.isEmpty(str) || delimLen == 0) { + return str; + } + str = str.toLowerCase(); + return capitalize(str, delimiters); + } + + //----------------------------------------------------------------------- + /** + *

Uncapitalizes all the whitespace separated words in a String. + * Only the first character of each word is changed.

+ * + *

Whitespace is defined by {@link Character#isWhitespace(char)}. + * A null input String returns null.

+ * + *
+     * WordUtils.uncapitalize(null)        = null
+     * WordUtils.uncapitalize("")          = ""
+     * WordUtils.uncapitalize("I Am FINE") = "i am fINE"
+     * 
+ * + * @param str the String to uncapitalize, may be null + * @return uncapitalized String, null if null String input + * @see #capitalize(String) + */ + public static String uncapitalize(final String str) { + return uncapitalize(str, null); + } + + /** + *

Uncapitalizes all the whitespace separated words in a String. + * Only the first character of each word is changed.

+ * + *

The delimiters represent a set of characters understood to separate words. + * The first string character and the first non-delimiter character after a + * delimiter will be uncapitalized.

+ * + *

Whitespace is defined by {@link Character#isWhitespace(char)}. + * A null input String returns null.

+ * + *
+     * WordUtils.uncapitalize(null, *)            = null
+     * WordUtils.uncapitalize("", *)              = ""
+     * WordUtils.uncapitalize(*, null)            = *
+     * WordUtils.uncapitalize(*, new char[0])     = *
+     * WordUtils.uncapitalize("I AM.FINE", {'.'}) = "i AM.fINE"
+     * 
+ * + * @param str the String to uncapitalize, may be null + * @param delimiters set of characters to determine uncapitalization, null means whitespace + * @return uncapitalized String, null if null String input + * @see #capitalize(String) + * @since 2.1 + */ + public static String uncapitalize(final String str, final char... delimiters) { + final int delimLen = delimiters == null ? -1 : delimiters.length; + if (StringUtils.isEmpty(str) || delimLen == 0) { + return str; + } + final char[] buffer = str.toCharArray(); + boolean uncapitalizeNext = true; + for (int i = 0; i < buffer.length; i++) { + final char ch = buffer[i]; + if (isDelimiter(ch, delimiters)) { + uncapitalizeNext = true; + } else if (uncapitalizeNext) { + buffer[i] = Character.toLowerCase(ch); + uncapitalizeNext = false; + } + } + return new String(buffer); + } + + //----------------------------------------------------------------------- + /** + *

Swaps the case of a String using a word based algorithm.

+ * + * + * + *

Whitespace is defined by {@link Character#isWhitespace(char)}. + * A null input String returns null.

+ * + *
+     * StringUtils.swapCase(null)                 = null
+     * StringUtils.swapCase("")                   = ""
+     * StringUtils.swapCase("The dog has a BONE") = "tHE DOG HAS A bone"
+     * 
+ * + * @param str the String to swap case, may be null + * @return the changed String, null if null String input + */ + public static String swapCase(final String str) { + if (StringUtils.isEmpty(str)) { + return str; + } + final char[] buffer = str.toCharArray(); + + boolean whitespace = true; + + for (int i = 0; i < buffer.length; i++) { + final char ch = buffer[i]; + if (Character.isUpperCase(ch)) { + buffer[i] = Character.toLowerCase(ch); + whitespace = false; + } else if (Character.isTitleCase(ch)) { + buffer[i] = Character.toLowerCase(ch); + whitespace = false; + } else if (Character.isLowerCase(ch)) { + if (whitespace) { + buffer[i] = Character.toTitleCase(ch); + whitespace = false; + } else { + buffer[i] = Character.toUpperCase(ch); + } + } else { + whitespace = Character.isWhitespace(ch); + } + } + return new String(buffer); + } + + //----------------------------------------------------------------------- + /** + *

Extracts the initial characters from each word in the String.

+ * + *

All first characters after whitespace are returned as a new string. + * Their case is not changed.

+ * + *

Whitespace is defined by {@link Character#isWhitespace(char)}. + * A null input String returns null.

+ * + *
+     * WordUtils.initials(null)             = null
+     * WordUtils.initials("")               = ""
+     * WordUtils.initials("Ben John Lee")   = "BJL"
+     * WordUtils.initials("Ben J.Lee")      = "BJ"
+     * 
+ * + * @param str the String to get initials from, may be null + * @return String of initial letters, null if null String input + * @see #initials(String,char[]) + * @since 2.2 + */ + public static String initials(final String str) { + return initials(str, null); + } + + /** + *

Extracts the initial characters from each word in the String.

+ * + *

All first characters after the defined delimiters are returned as a new string. + * Their case is not changed.

+ * + *

If the delimiters array is null, then Whitespace is used. + * Whitespace is defined by {@link Character#isWhitespace(char)}. + * A null input String returns null. + * An empty delimiter array returns an empty String.

+ * + *
+     * WordUtils.initials(null, *)                = null
+     * WordUtils.initials("", *)                  = ""
+     * WordUtils.initials("Ben John Lee", null)   = "BJL"
+     * WordUtils.initials("Ben J.Lee", null)      = "BJ"
+     * WordUtils.initials("Ben J.Lee", [' ','.']) = "BJL"
+     * WordUtils.initials(*, new char[0])         = ""
+     * 
+ * + * @param str the String to get initials from, may be null + * @param delimiters set of characters to determine words, null means whitespace + * @return String of initial characters, null if null String input + * @see #initials(String) + * @since 2.2 + */ + public static String initials(final String str, final char... delimiters) { + if (StringUtils.isEmpty(str)) { + return str; + } + if (delimiters != null && delimiters.length == 0) { + return StringUtils.EMPTY; + } + final int strLen = str.length(); + final char[] buf = new char[strLen / 2 + 1]; + int count = 0; + boolean lastWasGap = true; + for (int i = 0; i < strLen; i++) { + final char ch = str.charAt(i); + + if (isDelimiter(ch, delimiters)) { + lastWasGap = true; + } else if (lastWasGap) { + buf[count++] = ch; + lastWasGap = false; + } else { + continue; // ignore ch + } + } + return new String(buf, 0, count); + } + + //----------------------------------------------------------------------- + /** + *

Checks if the String contains all words in the given array.

+ * + *

+ * A {@code null} String will return {@code false}. A {@code null}, zero + * length search array or if one element of array is null will return {@code false}. + *

+ * + *
+     * WordUtils.containsAllWords(null, *)            = false
+     * WordUtils.containsAllWords("", *)              = false
+     * WordUtils.containsAllWords(*, null)            = false
+     * WordUtils.containsAllWords(*, [])              = false
+     * WordUtils.containsAllWords("abcd", "ab", "cd") = false
+     * WordUtils.containsAllWords("abc def", "def", "abc") = true
+     * 
+ * + * + * @param word The CharSequence to check, may be null + * @param words The array of String words to search for, may be null + * @return {@code true} if all search words are found, {@code false} otherwise + * @since 3.5 + */ + public static boolean containsAllWords(CharSequence word, CharSequence... words) { + if (StringUtils.isEmpty(word) || ArrayUtils.isEmpty(words)) { + return false; + } + for (CharSequence w : words) { + if (StringUtils.isBlank(w)) { + return false; + } + Pattern p = Pattern.compile(".*\\b" + w + "\\b.*"); + if (!p.matcher(word).matches()) { + return false; + } + } + return true; + } + + //----------------------------------------------------------------------- + /** + * Is the character a delimiter. + * + * @param ch the character to check + * @param delimiters the delimiters + * @return true if it is a delimiter + */ +// ----------------------------------------------------------------------- +/** + * Is the character a delimiter. + * + * @param ch + * the character to check + * @param delimiters + * the delimiters + * @return true if it is a delimiter + */ +private static boolean isDelimiter(final char ch, final char[] delimiters) { + { + for (final char delimiter : /* NPEX_NULL_EXP */ + delimiters) { + if (ch == delimiter) { + return true; + } + } + return false; + } +} + +} diff --git a/Java/commons-lang-WordUtils_726/metadata.json b/Java/commons-lang-WordUtils_726/metadata.json new file mode 100644 index 000000000..77a11f8cd --- /dev/null +++ b/Java/commons-lang-WordUtils_726/metadata.json @@ -0,0 +1,21 @@ +{ + "language": "java", + "id": "commons-lang-WordUtils_726", + "buggyPath": ".", + "referencePath": null, + "buildCommand": "mvn package -V -B -Denforcer.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true -Drat.skip=true -Dlicense.skip=true -Dfindbugs.skip=true -Dgpg.skip=true -Dskip.npm=true -Dskip.gulp=true -Dskip.bower=true -Drat.numUnapprovedLicenses=100 -DskipTests=true -DskipITs=true -Dtest=None -DfailIfNoTests=false", + "testCommand": "mvn test -V -B -Denforcer.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true -Drat.skip=true -Dlicense.skip=true -Dfindbugs.skip=true -Dgpg.skip=true -Dskip.npm=true -Dskip.gulp=true -Dskip.bower=true -Drat.numUnapprovedLicenses=100", + "categories": [ + "safety", + "npe" + ], + "npe": { + "filepath": "src/main/java/org/apache/commons/lang3/text/WordUtils.java", + "line": 738, + "npe_method": "isDelimiter", + "deref_field": "delimiters", + "npe_class": "WordUtils", + "repo": "commons-lang", + "bug_id": "WordUtils_726" + } +} diff --git a/Java/commons-lang-WordUtils_726/npe.json b/Java/commons-lang-WordUtils_726/npe.json new file mode 100644 index 000000000..50b1ad590 --- /dev/null +++ b/Java/commons-lang-WordUtils_726/npe.json @@ -0,0 +1,7 @@ +{ + "filepath": "src/main/java/org/apache/commons/lang3/text/WordUtils.java", + "line": 738, + "npe_method": "isDelimiter", + "deref_field": "delimiters", + "npe_class": "WordUtils" +} \ No newline at end of file From c74d4047975694b50686adf8e222c4ad5c24a1a9 Mon Sep 17 00:00:00 2001 From: Seokhyun Lee <7948302+henrylee97@users.noreply.github.com> Date: Fri, 1 Dec 2023 10:07:19 +0900 Subject: [PATCH 3/4] refactor(java): commons-lang R-classes (#144) --- .../Dockerfile | 18 + .../buggy.java | 483 ++++++++++++ .../metadata.json | 21 + .../npe.json | 7 + .../Dockerfile | 18 + .../buggy.java | 486 ++++++++++++ .../metadata.json | 21 + .../npe.json | 7 + .../Dockerfile | 18 + .../buggy.java | 472 ++++++++++++ .../metadata.json | 21 + .../npe.json | 7 + .../Dockerfile | 18 + .../buggy.java | 470 +++++++++++ .../metadata.json | 21 + .../npe.json | 7 + Java/commons-lang-Range_219/Dockerfile | 18 + Java/commons-lang-Range_219/buggy.java | 496 ++++++++++++ Java/commons-lang-Range_219/metadata.json | 21 + Java/commons-lang-Range_219/npe.json | 7 + Java/commons-lang-Range_232/Dockerfile | 18 + Java/commons-lang-Range_232/buggy.java | 494 ++++++++++++ Java/commons-lang-Range_232/metadata.json | 21 + Java/commons-lang-Range_232/npe.json | 7 + Java/commons-lang-Range_245/Dockerfile | 18 + Java/commons-lang-Range_245/buggy.java | 494 ++++++++++++ Java/commons-lang-Range_245/metadata.json | 21 + Java/commons-lang-Range_245/npe.json | 7 + Java/commons-lang-Range_258/Dockerfile | 18 + Java/commons-lang-Range_258/buggy.java | 494 ++++++++++++ Java/commons-lang-Range_258/metadata.json | 21 + Java/commons-lang-Range_258/npe.json | 7 + Java/commons-lang-Range_271/Dockerfile | 18 + Java/commons-lang-Range_271/buggy.java | 494 ++++++++++++ Java/commons-lang-Range_271/metadata.json | 21 + Java/commons-lang-Range_271/npe.json | 7 + Java/commons-lang-Range_288/Dockerfile | 18 + Java/commons-lang-Range_288/buggy.java | 497 ++++++++++++ Java/commons-lang-Range_288/metadata.json | 21 + Java/commons-lang-Range_288/npe.json | 7 + Java/commons-lang-Range_314/Dockerfile | 18 + Java/commons-lang-Range_314/buggy.java | 499 ++++++++++++ Java/commons-lang-Range_314/metadata.json | 21 + Java/commons-lang-Range_314/npe.json | 7 + Java/commons-lang-Range_331/Dockerfile | 18 + Java/commons-lang-Range_331/buggy.java | 498 ++++++++++++ Java/commons-lang-Range_331/metadata.json | 21 + Java/commons-lang-Range_331/npe.json | 7 + Java/commons-lang-Range_350/Dockerfile | 18 + Java/commons-lang-Range_350/buggy.java | 499 ++++++++++++ Java/commons-lang-Range_350/metadata.json | 21 + Java/commons-lang-Range_350/npe.json | 7 + Java/commons-lang-Range_368/Dockerfile | 18 + Java/commons-lang-Range_368/buggy.java | 498 ++++++++++++ Java/commons-lang-Range_368/metadata.json | 21 + Java/commons-lang-Range_368/npe.json | 7 + .../Dockerfile | 18 + .../buggy.java | 728 +++++++++++++++++ .../metadata.json | 21 + .../npe.json | 7 + .../Dockerfile | 18 + .../buggy.java | 729 ++++++++++++++++++ .../metadata.json | 21 + .../npe.json | 7 + .../Dockerfile | 18 + .../buggy.java | 719 +++++++++++++++++ .../metadata.json | 21 + .../npe.json | 7 + .../Dockerfile | 18 + .../buggy.java | 725 +++++++++++++++++ .../metadata.json | 21 + .../npe.json | 7 + .../Dockerfile | 18 + .../buggy.java | 728 +++++++++++++++++ .../metadata.json | 21 + .../npe.json | 7 + 76 files changed, 11377 insertions(+) create mode 100644 Java/commons-lang-RandomStringUtils_355/Dockerfile create mode 100644 Java/commons-lang-RandomStringUtils_355/buggy.java create mode 100644 Java/commons-lang-RandomStringUtils_355/metadata.json create mode 100644 Java/commons-lang-RandomStringUtils_355/npe.json create mode 100644 Java/commons-lang-RandomStringUtils_376/Dockerfile create mode 100644 Java/commons-lang-RandomStringUtils_376/buggy.java create mode 100644 Java/commons-lang-RandomStringUtils_376/metadata.json create mode 100644 Java/commons-lang-RandomStringUtils_376/npe.json create mode 100644 Java/commons-lang-RandomStringUtils_430/Dockerfile create mode 100644 Java/commons-lang-RandomStringUtils_430/buggy.java create mode 100644 Java/commons-lang-RandomStringUtils_430/metadata.json create mode 100644 Java/commons-lang-RandomStringUtils_430/npe.json create mode 100644 Java/commons-lang-RandomStringUtils_449/Dockerfile create mode 100644 Java/commons-lang-RandomStringUtils_449/buggy.java create mode 100644 Java/commons-lang-RandomStringUtils_449/metadata.json create mode 100644 Java/commons-lang-RandomStringUtils_449/npe.json create mode 100644 Java/commons-lang-Range_219/Dockerfile create mode 100644 Java/commons-lang-Range_219/buggy.java create mode 100644 Java/commons-lang-Range_219/metadata.json create mode 100644 Java/commons-lang-Range_219/npe.json create mode 100644 Java/commons-lang-Range_232/Dockerfile create mode 100644 Java/commons-lang-Range_232/buggy.java create mode 100644 Java/commons-lang-Range_232/metadata.json create mode 100644 Java/commons-lang-Range_232/npe.json create mode 100644 Java/commons-lang-Range_245/Dockerfile create mode 100644 Java/commons-lang-Range_245/buggy.java create mode 100644 Java/commons-lang-Range_245/metadata.json create mode 100644 Java/commons-lang-Range_245/npe.json create mode 100644 Java/commons-lang-Range_258/Dockerfile create mode 100644 Java/commons-lang-Range_258/buggy.java create mode 100644 Java/commons-lang-Range_258/metadata.json create mode 100644 Java/commons-lang-Range_258/npe.json create mode 100644 Java/commons-lang-Range_271/Dockerfile create mode 100644 Java/commons-lang-Range_271/buggy.java create mode 100644 Java/commons-lang-Range_271/metadata.json create mode 100644 Java/commons-lang-Range_271/npe.json create mode 100644 Java/commons-lang-Range_288/Dockerfile create mode 100644 Java/commons-lang-Range_288/buggy.java create mode 100644 Java/commons-lang-Range_288/metadata.json create mode 100644 Java/commons-lang-Range_288/npe.json create mode 100644 Java/commons-lang-Range_314/Dockerfile create mode 100644 Java/commons-lang-Range_314/buggy.java create mode 100644 Java/commons-lang-Range_314/metadata.json create mode 100644 Java/commons-lang-Range_314/npe.json create mode 100644 Java/commons-lang-Range_331/Dockerfile create mode 100644 Java/commons-lang-Range_331/buggy.java create mode 100644 Java/commons-lang-Range_331/metadata.json create mode 100644 Java/commons-lang-Range_331/npe.json create mode 100644 Java/commons-lang-Range_350/Dockerfile create mode 100644 Java/commons-lang-Range_350/buggy.java create mode 100644 Java/commons-lang-Range_350/metadata.json create mode 100644 Java/commons-lang-Range_350/npe.json create mode 100644 Java/commons-lang-Range_368/Dockerfile create mode 100644 Java/commons-lang-Range_368/buggy.java create mode 100644 Java/commons-lang-Range_368/metadata.json create mode 100644 Java/commons-lang-Range_368/npe.json create mode 100644 Java/commons-lang-ReflectionToStringBuilder_327/Dockerfile create mode 100644 Java/commons-lang-ReflectionToStringBuilder_327/buggy.java create mode 100644 Java/commons-lang-ReflectionToStringBuilder_327/metadata.json create mode 100644 Java/commons-lang-ReflectionToStringBuilder_327/npe.json create mode 100644 Java/commons-lang-ReflectionToStringBuilder_345/Dockerfile create mode 100644 Java/commons-lang-ReflectionToStringBuilder_345/buggy.java create mode 100644 Java/commons-lang-ReflectionToStringBuilder_345/metadata.json create mode 100644 Java/commons-lang-ReflectionToStringBuilder_345/npe.json create mode 100644 Java/commons-lang-ReflectionToStringBuilder_367/Dockerfile create mode 100644 Java/commons-lang-ReflectionToStringBuilder_367/buggy.java create mode 100644 Java/commons-lang-ReflectionToStringBuilder_367/metadata.json create mode 100644 Java/commons-lang-ReflectionToStringBuilder_367/npe.json create mode 100644 Java/commons-lang-ReflectionToStringBuilder_670/Dockerfile create mode 100644 Java/commons-lang-ReflectionToStringBuilder_670/buggy.java create mode 100644 Java/commons-lang-ReflectionToStringBuilder_670/metadata.json create mode 100644 Java/commons-lang-ReflectionToStringBuilder_670/npe.json create mode 100644 Java/commons-lang-ReflectionToStringBuilder_689/Dockerfile create mode 100644 Java/commons-lang-ReflectionToStringBuilder_689/buggy.java create mode 100644 Java/commons-lang-ReflectionToStringBuilder_689/metadata.json create mode 100644 Java/commons-lang-ReflectionToStringBuilder_689/npe.json diff --git a/Java/commons-lang-RandomStringUtils_355/Dockerfile b/Java/commons-lang-RandomStringUtils_355/Dockerfile new file mode 100644 index 000000000..7b7fbe349 --- /dev/null +++ b/Java/commons-lang-RandomStringUtils_355/Dockerfile @@ -0,0 +1,18 @@ +FROM ghcr.io/kupl/starlab-benchmarks/java-base:commons-lang + +ENV TZ=Asia/Seoul + +COPY ./metadata.json . +COPY ./npe.json . +COPY ./buggy.java /tmp/buggy.java +RUN export BUGGY_PATH=$(cat metadata.json | jq -r ".npe.filepath") \ + && export BUGGY_LINE=$(cat metadata.json | jq -r ".npe.line") \ + && export BUGGY_MTHD=$(cat metadata.json | jq -r ".npe.npe_method") \ + && mv /tmp/buggy.java $BUGGY_PATH \ + && echo "[{\"filepath\": \"$BUGGY_PATH\", \"line\": $BUGGY_LINE, \"method_name\": \"$BUGGY_MTHD\"}]" | jq . > traces.json + +RUN git init . && git add -A + +RUN $(cat metadata.json | jq -r ".buildCommand") + +RUN $(cat metadata.json | jq -r ".testCommand"); if [ $? -eq 0 ]; then exit 1; fi diff --git a/Java/commons-lang-RandomStringUtils_355/buggy.java b/Java/commons-lang-RandomStringUtils_355/buggy.java new file mode 100644 index 000000000..027e22bb3 --- /dev/null +++ b/Java/commons-lang-RandomStringUtils_355/buggy.java @@ -0,0 +1,483 @@ +/* + * 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.Random; + +/** + *

Operations for random {@code String}s.

+ *

Currently private high surrogate 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.

+ * + *

#ThreadSafe#

+ * @since 1.0 + */ +public class RandomStringUtils { + + /** + *

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 Random RANDOM = new Random(); + + /** + *

{@code RandomStringUtils} instances should NOT be constructed in + * standard programming. Instead, the class should be used as + * {@code RandomStringUtils.random(5);}.

+ * + *

This constructor is public to permit tools that require a JavaBean instance + * to operate.

+ */ + public RandomStringUtils() { + super(); + } + + // Random + //----------------------------------------------------------------------- + /** + *

Creates a random string whose length is the number of characters + * specified.

+ * + *

Characters will be chosen from the set of all characters.

+ * + * @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); + } + + /** + *

Creates a random string whose length is the number of characters + * specified.

+ * + *

Characters will be chosen from the set of characters whose + * ASCII value is between {@code 32} and {@code 126} (inclusive).

+ * + * @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); + } + + /** + *

Creates a random string whose length is between the inclusive minimum and + * the exclusive maximum.

+ * + *

Characters will be chosen from the set of characters whose + * ASCII value is between {@code 32} and {@code 126} (inclusive).

+ * + * @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)); + } + + /** + *

Creates a random string whose length is the number of characters + * specified.

+ * + *

Characters will be chosen from the set of alphabetic + * characters.

+ * + * @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); + } + + /** + *

Creates a random string whose length is between the inclusive minimum and + * the exclusive maximum.

+ * + *

Characters will be chosen from the set of alphabetic characters.

+ * + * @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)); + } + + /** + *

Creates a random string whose length is the number of characters + * specified.

+ * + *

Characters will be chosen from the set of alpha-numeric + * characters.

+ * + * @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); + } + + /** + *

Creates a random string whose length is between the inclusive minimum and + * the exclusive maximum.

+ * + *

Characters will be chosen from the set of alpha-numeric characters.

+ * + * @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)); + } + + /** + *

Creates a random string whose length is the number of characters specified.

+ * + *

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).

+ * + * @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); + } + + /** + *

Creates a random string whose length is between the inclusive minimum and + * the exclusive maximum.

+ * + *

Characters will be chosen from the set of \p{Graph} characters.

+ * + * @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)); + } + + /** + *

Creates a random string whose length is the number of characters + * specified.

+ * + *

Characters will be chosen from the set of numeric + * characters.

+ * + * @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); + } + + /** + *

Creates a random string whose length is between the inclusive minimum and + * the exclusive maximum.

+ * + *

Characters will be chosen from the set of \p{Digit} characters.

+ * + * @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)); + } + + /** + *

Creates a random string whose length is the number of characters specified.

+ * + *

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).

+ * + * @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); + } + + /** + *

Creates a random string whose length is between the inclusive minimum and + * the exclusive maximum.

+ * + *

Characters will be chosen from the set of \p{Print} characters.

+ * + * @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)); + } + + /** + *

Creates a random string whose length is the number of characters + * specified.

+ * + *

Characters will be chosen from the set of alpha-numeric + * characters as indicated by the arguments.

+ * + * @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); + } + + /** + *

Creates a random string whose length is the number of characters + * specified.

+ * + *

Characters will be chosen from the set of alpha-numeric + * characters as indicated by the arguments.

+ * + * @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); + } + + /** + *

Creates a random string based on a variety of options, using + * default source of randomness.

+ * + *

This method has exactly the same semantics as + * {@link #random(int,int,int,boolean,boolean,char[],Random)}, but + * instead of using an externally supplied source of randomness, it uses + * the internal static {@link Random} instance.

+ * + * @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 only allow letters? + * @param numbers only allow numbers? + * @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); + } + + /** + *

Creates a random string based on a variety of options, using + * supplied source of randomness.

+ * + *

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 {@code Integer.MAX_VALUE}. + * + *

If set is not {@code null}, characters between start and + * end are chosen.

+ * + *

This method accepts a user-supplied {@link Random} + * instance to use as a source of randomness. By seeding a single + * {@link Random} instance with a fixed seed and using it for each call, + * the same random sequence of strings can be generated repeatedly + * and predictably.

+ * + * @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 only allow letters? + * @param numbers only allow numbers? + * @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 + */ +/** + *

Creates a random string based on a variety of options, using + * supplied source of randomness.

+ * + *

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 {@code Integer.MAX_VALUE}. + * + *

If set is not {@code null}, characters between start and + * end are chosen.

+ * + *

This method accepts a user-supplied {@link Random} + * instance to use as a source of randomness. By seeding a single + * {@link Random} instance with a fixed seed and using it for each call, + * the same random sequence of strings can be generated repeatedly + * and predictably.

+ * + * @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 + * only allow letters? + * @param numbers + * only allow numbers? + * @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 java.lang.String random(int count, int start, int end, final boolean letters, final boolean numbers, final char[] chars, final java.util.Random random) { + if (count == 0) { + return org.apache.commons.lang3.StringUtils.EMPTY; + } else if (count < 0) { + throw new java.lang.IllegalArgumentException(("Requested random string length " + count) + " is less than 0."); + } + if ((chars != null) && (chars.length == 0)) { + throw new java.lang.IllegalArgumentException("The chars array must not be empty"); + } + if ((start == 0) && (end == 0)) { + { + end = /* NPEX_NULL_EXP */ + chars.length; + } + } else if (end <= start) { + throw new java.lang.IllegalArgumentException(((("Parameter end (" + end) + ") must be greater than start (") + start) + ")"); + } + final char[] buffer = new char[count]; + final int gap = end - start; + while ((count--) != 0) { + char ch; + if (chars == null) { + ch = ((char) (random.nextInt(gap) + start)); + } else { + ch = chars[random.nextInt(gap) + start]; + } + if (((letters && java.lang.Character.isLetter(ch)) || (numbers && java.lang.Character.isDigit(ch))) || ((!letters) && (!numbers))) { + if ((ch >= 56320) && (ch <= 57343)) { + if (count == 0) { + count++; + } else { + // low surrogate, insert high surrogate after putting it in + buffer[count] = ch; + count--; + buffer[count] = ((char) (55296 + random.nextInt(128))); + } + } else if ((ch >= 55296) && (ch <= 56191)) { + if (count == 0) { + count++; + } else { + // high surrogate, insert low surrogate before putting it in + buffer[count] = ((char) (56320 + random.nextInt(128))); + count--; + buffer[count] = ch; + } + } else if ((ch >= 56192) && (ch <= 56319)) { + // private high surrogate, no effing clue, so skip it + count++; + } else { + buffer[count] = ch; + } + } else { + count++; + } + } + return new java.lang.String(buffer); +} + + /** + *

Creates a random string whose length is the number of characters + * specified.

+ * + *

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.

+ * + * @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()); + } + + /** + *

Creates a random string whose length is the number of characters + * specified.

+ * + *

Characters will be chosen from the set of characters specified.

+ * + * @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); + } + +} diff --git a/Java/commons-lang-RandomStringUtils_355/metadata.json b/Java/commons-lang-RandomStringUtils_355/metadata.json new file mode 100644 index 000000000..b9bb1cb61 --- /dev/null +++ b/Java/commons-lang-RandomStringUtils_355/metadata.json @@ -0,0 +1,21 @@ +{ + "language": "java", + "id": "commons-lang-RandomStringUtils_355", + "buggyPath": ".", + "referencePath": null, + "buildCommand": "mvn package -V -B -Denforcer.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true -Drat.skip=true -Dlicense.skip=true -Dfindbugs.skip=true -Dgpg.skip=true -Dskip.npm=true -Dskip.gulp=true -Dskip.bower=true -Drat.numUnapprovedLicenses=100 -DskipTests=true -DskipITs=true -Dtest=None -DfailIfNoTests=false", + "testCommand": "mvn test -V -B -Denforcer.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true -Drat.skip=true -Dlicense.skip=true -Dfindbugs.skip=true -Dgpg.skip=true -Dskip.npm=true -Dskip.gulp=true -Dskip.bower=true -Drat.numUnapprovedLicenses=100", + "categories": [ + "safety", + "npe" + ], + "npe": { + "filepath": "src/main/java/org/apache/commons/lang3/RandomStringUtils.java", + "line": 397, + "npe_method": "random", + "deref_field": "chars", + "npe_class": "RandomStringUtils", + "repo": "commons-lang", + "bug_id": "RandomStringUtils_355" + } +} diff --git a/Java/commons-lang-RandomStringUtils_355/npe.json b/Java/commons-lang-RandomStringUtils_355/npe.json new file mode 100644 index 000000000..6bf885791 --- /dev/null +++ b/Java/commons-lang-RandomStringUtils_355/npe.json @@ -0,0 +1,7 @@ +{ + "filepath": "src/main/java/org/apache/commons/lang3/RandomStringUtils.java", + "line": 397, + "npe_method": "random", + "deref_field": "chars", + "npe_class": "RandomStringUtils" +} \ No newline at end of file diff --git a/Java/commons-lang-RandomStringUtils_376/Dockerfile b/Java/commons-lang-RandomStringUtils_376/Dockerfile new file mode 100644 index 000000000..7b7fbe349 --- /dev/null +++ b/Java/commons-lang-RandomStringUtils_376/Dockerfile @@ -0,0 +1,18 @@ +FROM ghcr.io/kupl/starlab-benchmarks/java-base:commons-lang + +ENV TZ=Asia/Seoul + +COPY ./metadata.json . +COPY ./npe.json . +COPY ./buggy.java /tmp/buggy.java +RUN export BUGGY_PATH=$(cat metadata.json | jq -r ".npe.filepath") \ + && export BUGGY_LINE=$(cat metadata.json | jq -r ".npe.line") \ + && export BUGGY_MTHD=$(cat metadata.json | jq -r ".npe.npe_method") \ + && mv /tmp/buggy.java $BUGGY_PATH \ + && echo "[{\"filepath\": \"$BUGGY_PATH\", \"line\": $BUGGY_LINE, \"method_name\": \"$BUGGY_MTHD\"}]" | jq . > traces.json + +RUN git init . && git add -A + +RUN $(cat metadata.json | jq -r ".buildCommand") + +RUN $(cat metadata.json | jq -r ".testCommand"); if [ $? -eq 0 ]; then exit 1; fi diff --git a/Java/commons-lang-RandomStringUtils_376/buggy.java b/Java/commons-lang-RandomStringUtils_376/buggy.java new file mode 100644 index 000000000..700d90d85 --- /dev/null +++ b/Java/commons-lang-RandomStringUtils_376/buggy.java @@ -0,0 +1,486 @@ +/* + * 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.Random; + +/** + *

Operations for random {@code String}s.

+ *

Currently private high surrogate 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.

+ * + *

#ThreadSafe#

+ * @since 1.0 + */ +public class RandomStringUtils { + + /** + *

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 Random RANDOM = new Random(); + + /** + *

{@code RandomStringUtils} instances should NOT be constructed in + * standard programming. Instead, the class should be used as + * {@code RandomStringUtils.random(5);}.

+ * + *

This constructor is public to permit tools that require a JavaBean instance + * to operate.

+ */ + public RandomStringUtils() { + super(); + } + + // Random + //----------------------------------------------------------------------- + /** + *

Creates a random string whose length is the number of characters + * specified.

+ * + *

Characters will be chosen from the set of all characters.

+ * + * @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); + } + + /** + *

Creates a random string whose length is the number of characters + * specified.

+ * + *

Characters will be chosen from the set of characters whose + * ASCII value is between {@code 32} and {@code 126} (inclusive).

+ * + * @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); + } + + /** + *

Creates a random string whose length is between the inclusive minimum and + * the exclusive maximum.

+ * + *

Characters will be chosen from the set of characters whose + * ASCII value is between {@code 32} and {@code 126} (inclusive).

+ * + * @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)); + } + + /** + *

Creates a random string whose length is the number of characters + * specified.

+ * + *

Characters will be chosen from the set of alphabetic + * characters.

+ * + * @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); + } + + /** + *

Creates a random string whose length is between the inclusive minimum and + * the exclusive maximum.

+ * + *

Characters will be chosen from the set of alphabetic characters.

+ * + * @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)); + } + + /** + *

Creates a random string whose length is the number of characters + * specified.

+ * + *

Characters will be chosen from the set of alpha-numeric + * characters.

+ * + * @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); + } + + /** + *

Creates a random string whose length is between the inclusive minimum and + * the exclusive maximum.

+ * + *

Characters will be chosen from the set of alpha-numeric characters.

+ * + * @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)); + } + + /** + *

Creates a random string whose length is the number of characters specified.

+ * + *

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).

+ * + * @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); + } + + /** + *

Creates a random string whose length is between the inclusive minimum and + * the exclusive maximum.

+ * + *

Characters will be chosen from the set of \p{Graph} characters.

+ * + * @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)); + } + + /** + *

Creates a random string whose length is the number of characters + * specified.

+ * + *

Characters will be chosen from the set of numeric + * characters.

+ * + * @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); + } + + /** + *

Creates a random string whose length is between the inclusive minimum and + * the exclusive maximum.

+ * + *

Characters will be chosen from the set of \p{Digit} characters.

+ * + * @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)); + } + + /** + *

Creates a random string whose length is the number of characters specified.

+ * + *

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).

+ * + * @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); + } + + /** + *

Creates a random string whose length is between the inclusive minimum and + * the exclusive maximum.

+ * + *

Characters will be chosen from the set of \p{Print} characters.

+ * + * @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)); + } + + /** + *

Creates a random string whose length is the number of characters + * specified.

+ * + *

Characters will be chosen from the set of alpha-numeric + * characters as indicated by the arguments.

+ * + * @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); + } + + /** + *

Creates a random string whose length is the number of characters + * specified.

+ * + *

Characters will be chosen from the set of alpha-numeric + * characters as indicated by the arguments.

+ * + * @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); + } + + /** + *

Creates a random string based on a variety of options, using + * default source of randomness.

+ * + *

This method has exactly the same semantics as + * {@link #random(int,int,int,boolean,boolean,char[],Random)}, but + * instead of using an externally supplied source of randomness, it uses + * the internal static {@link Random} instance.

+ * + * @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 only allow letters? + * @param numbers only allow numbers? + * @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); + } + + /** + *

Creates a random string based on a variety of options, using + * supplied source of randomness.

+ * + *

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 {@code Integer.MAX_VALUE}. + * + *

If set is not {@code null}, characters between start and + * end are chosen.

+ * + *

This method accepts a user-supplied {@link Random} + * instance to use as a source of randomness. By seeding a single + * {@link Random} instance with a fixed seed and using it for each call, + * the same random sequence of strings can be generated repeatedly + * and predictably.

+ * + * @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 only allow letters? + * @param numbers only allow numbers? + * @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 + */ +/** + *

Creates a random string based on a variety of options, using + * supplied source of randomness.

+ * + *

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 {@code Integer.MAX_VALUE}. + * + *

If set is not {@code null}, characters between start and + * end are chosen.

+ * + *

This method accepts a user-supplied {@link Random} + * instance to use as a source of randomness. By seeding a single + * {@link Random} instance with a fixed seed and using it for each call, + * the same random sequence of strings can be generated repeatedly + * and predictably.

+ * + * @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 + * only allow letters? + * @param numbers + * only allow numbers? + * @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 java.lang.String random(int count, int start, int end, final boolean letters, final boolean numbers, final char[] chars, final java.util.Random random) { + if (count == 0) { + return org.apache.commons.lang3.StringUtils.EMPTY; + } else if (count < 0) { + throw new java.lang.IllegalArgumentException(("Requested random string length " + count) + " is less than 0."); + } + if ((chars != null) && (chars.length == 0)) { + throw new java.lang.IllegalArgumentException("The chars array must not be empty"); + } + if ((start == 0) && (end == 0)) { + if (chars != null) { + end = chars.length; + } else if ((!letters) && (!numbers)) { + end = java.lang.Integer.MAX_VALUE; + } else { + end = 'z' + 1; + start = ' '; + } + } else if (end <= start) { + throw new java.lang.IllegalArgumentException(((("Parameter end (" + end) + ") must be greater than start (") + start) + ")"); + } + final char[] buffer = new char[count]; + final int gap = end - start; + while ((count--) != 0) { + char ch; + { + ch = /* NPEX_NULL_EXP */ + chars[random.nextInt(gap) + start]; + } + if (((letters && java.lang.Character.isLetter(ch)) || (numbers && java.lang.Character.isDigit(ch))) || ((!letters) && (!numbers))) { + if ((ch >= 56320) && (ch <= 57343)) { + if (count == 0) { + count++; + } else { + // low surrogate, insert high surrogate after putting it in + buffer[count] = ch; + count--; + buffer[count] = ((char) (55296 + random.nextInt(128))); + } + } else if ((ch >= 55296) && (ch <= 56191)) { + if (count == 0) { + count++; + } else { + // high surrogate, insert low surrogate before putting it in + buffer[count] = ((char) (56320 + random.nextInt(128))); + count--; + buffer[count] = ch; + } + } else if ((ch >= 56192) && (ch <= 56319)) { + // private high surrogate, no effing clue, so skip it + count++; + } else { + buffer[count] = ch; + } + } else { + count++; + } + } + return new java.lang.String(buffer); +} + + /** + *

Creates a random string whose length is the number of characters + * specified.

+ * + *

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.

+ * + * @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()); + } + + /** + *

Creates a random string whose length is the number of characters + * specified.

+ * + *

Characters will be chosen from the set of characters specified.

+ * + * @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); + } + +} diff --git a/Java/commons-lang-RandomStringUtils_376/metadata.json b/Java/commons-lang-RandomStringUtils_376/metadata.json new file mode 100644 index 000000000..eb182e75c --- /dev/null +++ b/Java/commons-lang-RandomStringUtils_376/metadata.json @@ -0,0 +1,21 @@ +{ + "language": "java", + "id": "commons-lang-RandomStringUtils_376", + "buggyPath": ".", + "referencePath": null, + "buildCommand": "mvn package -V -B -Denforcer.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true -Drat.skip=true -Dlicense.skip=true -Dfindbugs.skip=true -Dgpg.skip=true -Dskip.npm=true -Dskip.gulp=true -Dskip.bower=true -Drat.numUnapprovedLicenses=100 -DskipTests=true -DskipITs=true -Dtest=None -DfailIfNoTests=false", + "testCommand": "mvn test -V -B -Denforcer.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true -Drat.skip=true -Dlicense.skip=true -Dfindbugs.skip=true -Dgpg.skip=true -Dskip.npm=true -Dskip.gulp=true -Dskip.bower=true -Drat.numUnapprovedLicenses=100", + "categories": [ + "safety", + "npe" + ], + "npe": { + "filepath": "src/main/java/org/apache/commons/lang3/RandomStringUtils.java", + "line": 412, + "npe_method": "random", + "deref_field": "chars", + "npe_class": "RandomStringUtils", + "repo": "commons-lang", + "bug_id": "RandomStringUtils_376" + } +} diff --git a/Java/commons-lang-RandomStringUtils_376/npe.json b/Java/commons-lang-RandomStringUtils_376/npe.json new file mode 100644 index 000000000..7fdf74177 --- /dev/null +++ b/Java/commons-lang-RandomStringUtils_376/npe.json @@ -0,0 +1,7 @@ +{ + "filepath": "src/main/java/org/apache/commons/lang3/RandomStringUtils.java", + "line": 412, + "npe_method": "random", + "deref_field": "chars", + "npe_class": "RandomStringUtils" +} \ No newline at end of file diff --git a/Java/commons-lang-RandomStringUtils_430/Dockerfile b/Java/commons-lang-RandomStringUtils_430/Dockerfile new file mode 100644 index 000000000..7b7fbe349 --- /dev/null +++ b/Java/commons-lang-RandomStringUtils_430/Dockerfile @@ -0,0 +1,18 @@ +FROM ghcr.io/kupl/starlab-benchmarks/java-base:commons-lang + +ENV TZ=Asia/Seoul + +COPY ./metadata.json . +COPY ./npe.json . +COPY ./buggy.java /tmp/buggy.java +RUN export BUGGY_PATH=$(cat metadata.json | jq -r ".npe.filepath") \ + && export BUGGY_LINE=$(cat metadata.json | jq -r ".npe.line") \ + && export BUGGY_MTHD=$(cat metadata.json | jq -r ".npe.npe_method") \ + && mv /tmp/buggy.java $BUGGY_PATH \ + && echo "[{\"filepath\": \"$BUGGY_PATH\", \"line\": $BUGGY_LINE, \"method_name\": \"$BUGGY_MTHD\"}]" | jq . > traces.json + +RUN git init . && git add -A + +RUN $(cat metadata.json | jq -r ".buildCommand") + +RUN $(cat metadata.json | jq -r ".testCommand"); if [ $? -eq 0 ]; then exit 1; fi diff --git a/Java/commons-lang-RandomStringUtils_430/buggy.java b/Java/commons-lang-RandomStringUtils_430/buggy.java new file mode 100644 index 000000000..c1b46b068 --- /dev/null +++ b/Java/commons-lang-RandomStringUtils_430/buggy.java @@ -0,0 +1,472 @@ +/* + * 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.Random; + +/** + *

Operations for random {@code String}s.

+ *

Currently private high surrogate 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.

+ * + *

#ThreadSafe#

+ * @since 1.0 + */ +public class RandomStringUtils { + + /** + *

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 Random RANDOM = new Random(); + + /** + *

{@code RandomStringUtils} instances should NOT be constructed in + * standard programming. Instead, the class should be used as + * {@code RandomStringUtils.random(5);}.

+ * + *

This constructor is public to permit tools that require a JavaBean instance + * to operate.

+ */ + public RandomStringUtils() { + super(); + } + + // Random + //----------------------------------------------------------------------- + /** + *

Creates a random string whose length is the number of characters + * specified.

+ * + *

Characters will be chosen from the set of all characters.

+ * + * @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); + } + + /** + *

Creates a random string whose length is the number of characters + * specified.

+ * + *

Characters will be chosen from the set of characters whose + * ASCII value is between {@code 32} and {@code 126} (inclusive).

+ * + * @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); + } + + /** + *

Creates a random string whose length is between the inclusive minimum and + * the exclusive maximum.

+ * + *

Characters will be chosen from the set of characters whose + * ASCII value is between {@code 32} and {@code 126} (inclusive).

+ * + * @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)); + } + + /** + *

Creates a random string whose length is the number of characters + * specified.

+ * + *

Characters will be chosen from the set of alphabetic + * characters.

+ * + * @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); + } + + /** + *

Creates a random string whose length is between the inclusive minimum and + * the exclusive maximum.

+ * + *

Characters will be chosen from the set of alphabetic characters.

+ * + * @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)); + } + + /** + *

Creates a random string whose length is the number of characters + * specified.

+ * + *

Characters will be chosen from the set of alpha-numeric + * characters.

+ * + * @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); + } + + /** + *

Creates a random string whose length is between the inclusive minimum and + * the exclusive maximum.

+ * + *

Characters will be chosen from the set of alpha-numeric characters.

+ * + * @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)); + } + + /** + *

Creates a random string whose length is the number of characters specified.

+ * + *

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).

+ * + * @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); + } + + /** + *

Creates a random string whose length is between the inclusive minimum and + * the exclusive maximum.

+ * + *

Characters will be chosen from the set of \p{Graph} characters.

+ * + * @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)); + } + + /** + *

Creates a random string whose length is the number of characters + * specified.

+ * + *

Characters will be chosen from the set of numeric + * characters.

+ * + * @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); + } + + /** + *

Creates a random string whose length is between the inclusive minimum and + * the exclusive maximum.

+ * + *

Characters will be chosen from the set of \p{Digit} characters.

+ * + * @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)); + } + + /** + *

Creates a random string whose length is the number of characters specified.

+ * + *

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).

+ * + * @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); + } + + /** + *

Creates a random string whose length is between the inclusive minimum and + * the exclusive maximum.

+ * + *

Characters will be chosen from the set of \p{Print} characters.

+ * + * @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)); + } + + /** + *

Creates a random string whose length is the number of characters + * specified.

+ * + *

Characters will be chosen from the set of alpha-numeric + * characters as indicated by the arguments.

+ * + * @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); + } + + /** + *

Creates a random string whose length is the number of characters + * specified.

+ * + *

Characters will be chosen from the set of alpha-numeric + * characters as indicated by the arguments.

+ * + * @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); + } + + /** + *

Creates a random string based on a variety of options, using + * default source of randomness.

+ * + *

This method has exactly the same semantics as + * {@link #random(int,int,int,boolean,boolean,char[],Random)}, but + * instead of using an externally supplied source of randomness, it uses + * the internal static {@link Random} instance.

+ * + * @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 only allow letters? + * @param numbers only allow numbers? + * @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); + } + + /** + *

Creates a random string based on a variety of options, using + * supplied source of randomness.

+ * + *

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 {@code Integer.MAX_VALUE}. + * + *

If set is not {@code null}, characters between start and + * end are chosen.

+ * + *

This method accepts a user-supplied {@link Random} + * instance to use as a source of randomness. By seeding a single + * {@link Random} instance with a fixed seed and using it for each call, + * the same random sequence of strings can be generated repeatedly + * and predictably.

+ * + * @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 only allow letters? + * @param numbers only allow numbers? + * @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 Random 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 = Integer.MAX_VALUE; + } else { + end = 'z' + 1; + start = ' '; + } + } + } else { + if (end <= start) { + throw new IllegalArgumentException("Parameter end (" + end + ") must be greater than start (" + start + ")"); + } + } + + final char[] buffer = new char[count]; + final int gap = end - start; + + while (count-- != 0) { + char ch; + if (chars == null) { + ch = (char) (random.nextInt(gap) + start); + } else { + ch = chars[random.nextInt(gap) + start]; + } + if (letters && Character.isLetter(ch) + || numbers && Character.isDigit(ch) + || !letters && !numbers) { + if(ch >= 56320 && ch <= 57343) { + if(count == 0) { + count++; + } else { + // low surrogate, insert high surrogate after putting it in + buffer[count] = ch; + count--; + buffer[count] = (char) (55296 + random.nextInt(128)); + } + } else if(ch >= 55296 && ch <= 56191) { + if(count == 0) { + count++; + } else { + // high surrogate, insert low surrogate before putting it in + buffer[count] = (char) (56320 + random.nextInt(128)); + count--; + buffer[count] = ch; + } + } else if(ch >= 56192 && ch <= 56319) { + // private high surrogate, no effing clue, so skip it + count++; + } else { + buffer[count] = ch; + } + } else { + count++; + } + } + return new String(buffer); + } + + /** + *

Creates a random string whose length is the number of characters + * specified.

+ * + *

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.

+ * + * @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. + */ +/** + *

Creates a random string whose length is the number of characters + * specified.

+ * + *

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.

+ * + * @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 java.lang.String random(final int count, final java.lang.String chars) { + { + return org.apache.commons.lang3.RandomStringUtils.random(count, /* NPEX_NULL_EXP */ + chars.toCharArray()); + } +} + + /** + *

Creates a random string whose length is the number of characters + * specified.

+ * + *

Characters will be chosen from the set of characters specified.

+ * + * @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); + } + +} diff --git a/Java/commons-lang-RandomStringUtils_430/metadata.json b/Java/commons-lang-RandomStringUtils_430/metadata.json new file mode 100644 index 000000000..23d330ded --- /dev/null +++ b/Java/commons-lang-RandomStringUtils_430/metadata.json @@ -0,0 +1,21 @@ +{ + "language": "java", + "id": "commons-lang-RandomStringUtils_430", + "buggyPath": ".", + "referencePath": null, + "buildCommand": "mvn package -V -B -Denforcer.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true -Drat.skip=true -Dlicense.skip=true -Dfindbugs.skip=true -Dgpg.skip=true -Dskip.npm=true -Dskip.gulp=true -Dskip.bower=true -Drat.numUnapprovedLicenses=100 -DskipTests=true -DskipITs=true -Dtest=None -DfailIfNoTests=false", + "testCommand": "mvn test -V -B -Denforcer.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true -Drat.skip=true -Dlicense.skip=true -Dfindbugs.skip=true -Dgpg.skip=true -Dskip.npm=true -Dskip.gulp=true -Dskip.bower=true -Drat.numUnapprovedLicenses=100", + "categories": [ + "safety", + "npe" + ], + "npe": { + "filepath": "src/main/java/org/apache/commons/lang3/RandomStringUtils.java", + "line": 449, + "npe_method": "random", + "deref_field": "chars", + "npe_class": "RandomStringUtils", + "repo": "commons-lang", + "bug_id": "RandomStringUtils_430" + } +} diff --git a/Java/commons-lang-RandomStringUtils_430/npe.json b/Java/commons-lang-RandomStringUtils_430/npe.json new file mode 100644 index 000000000..ff37deba0 --- /dev/null +++ b/Java/commons-lang-RandomStringUtils_430/npe.json @@ -0,0 +1,7 @@ +{ + "filepath": "src/main/java/org/apache/commons/lang3/RandomStringUtils.java", + "line": 449, + "npe_method": "random", + "deref_field": "chars", + "npe_class": "RandomStringUtils" +} \ No newline at end of file diff --git a/Java/commons-lang-RandomStringUtils_449/Dockerfile b/Java/commons-lang-RandomStringUtils_449/Dockerfile new file mode 100644 index 000000000..7b7fbe349 --- /dev/null +++ b/Java/commons-lang-RandomStringUtils_449/Dockerfile @@ -0,0 +1,18 @@ +FROM ghcr.io/kupl/starlab-benchmarks/java-base:commons-lang + +ENV TZ=Asia/Seoul + +COPY ./metadata.json . +COPY ./npe.json . +COPY ./buggy.java /tmp/buggy.java +RUN export BUGGY_PATH=$(cat metadata.json | jq -r ".npe.filepath") \ + && export BUGGY_LINE=$(cat metadata.json | jq -r ".npe.line") \ + && export BUGGY_MTHD=$(cat metadata.json | jq -r ".npe.npe_method") \ + && mv /tmp/buggy.java $BUGGY_PATH \ + && echo "[{\"filepath\": \"$BUGGY_PATH\", \"line\": $BUGGY_LINE, \"method_name\": \"$BUGGY_MTHD\"}]" | jq . > traces.json + +RUN git init . && git add -A + +RUN $(cat metadata.json | jq -r ".buildCommand") + +RUN $(cat metadata.json | jq -r ".testCommand"); if [ $? -eq 0 ]; then exit 1; fi diff --git a/Java/commons-lang-RandomStringUtils_449/buggy.java b/Java/commons-lang-RandomStringUtils_449/buggy.java new file mode 100644 index 000000000..db3aecf7d --- /dev/null +++ b/Java/commons-lang-RandomStringUtils_449/buggy.java @@ -0,0 +1,470 @@ +/* + * 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.Random; + +/** + *

Operations for random {@code String}s.

+ *

Currently private high surrogate 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.

+ * + *

#ThreadSafe#

+ * @since 1.0 + */ +public class RandomStringUtils { + + /** + *

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 Random RANDOM = new Random(); + + /** + *

{@code RandomStringUtils} instances should NOT be constructed in + * standard programming. Instead, the class should be used as + * {@code RandomStringUtils.random(5);}.

+ * + *

This constructor is public to permit tools that require a JavaBean instance + * to operate.

+ */ + public RandomStringUtils() { + super(); + } + + // Random + //----------------------------------------------------------------------- + /** + *

Creates a random string whose length is the number of characters + * specified.

+ * + *

Characters will be chosen from the set of all characters.

+ * + * @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); + } + + /** + *

Creates a random string whose length is the number of characters + * specified.

+ * + *

Characters will be chosen from the set of characters whose + * ASCII value is between {@code 32} and {@code 126} (inclusive).

+ * + * @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); + } + + /** + *

Creates a random string whose length is between the inclusive minimum and + * the exclusive maximum.

+ * + *

Characters will be chosen from the set of characters whose + * ASCII value is between {@code 32} and {@code 126} (inclusive).

+ * + * @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)); + } + + /** + *

Creates a random string whose length is the number of characters + * specified.

+ * + *

Characters will be chosen from the set of alphabetic + * characters.

+ * + * @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); + } + + /** + *

Creates a random string whose length is between the inclusive minimum and + * the exclusive maximum.

+ * + *

Characters will be chosen from the set of alphabetic characters.

+ * + * @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)); + } + + /** + *

Creates a random string whose length is the number of characters + * specified.

+ * + *

Characters will be chosen from the set of alpha-numeric + * characters.

+ * + * @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); + } + + /** + *

Creates a random string whose length is between the inclusive minimum and + * the exclusive maximum.

+ * + *

Characters will be chosen from the set of alpha-numeric characters.

+ * + * @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)); + } + + /** + *

Creates a random string whose length is the number of characters specified.

+ * + *

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).

+ * + * @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); + } + + /** + *

Creates a random string whose length is between the inclusive minimum and + * the exclusive maximum.

+ * + *

Characters will be chosen from the set of \p{Graph} characters.

+ * + * @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)); + } + + /** + *

Creates a random string whose length is the number of characters + * specified.

+ * + *

Characters will be chosen from the set of numeric + * characters.

+ * + * @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); + } + + /** + *

Creates a random string whose length is between the inclusive minimum and + * the exclusive maximum.

+ * + *

Characters will be chosen from the set of \p{Digit} characters.

+ * + * @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)); + } + + /** + *

Creates a random string whose length is the number of characters specified.

+ * + *

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).

+ * + * @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); + } + + /** + *

Creates a random string whose length is between the inclusive minimum and + * the exclusive maximum.

+ * + *

Characters will be chosen from the set of \p{Print} characters.

+ * + * @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)); + } + + /** + *

Creates a random string whose length is the number of characters + * specified.

+ * + *

Characters will be chosen from the set of alpha-numeric + * characters as indicated by the arguments.

+ * + * @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); + } + + /** + *

Creates a random string whose length is the number of characters + * specified.

+ * + *

Characters will be chosen from the set of alpha-numeric + * characters as indicated by the arguments.

+ * + * @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); + } + + /** + *

Creates a random string based on a variety of options, using + * default source of randomness.

+ * + *

This method has exactly the same semantics as + * {@link #random(int,int,int,boolean,boolean,char[],Random)}, but + * instead of using an externally supplied source of randomness, it uses + * the internal static {@link Random} instance.

+ * + * @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 only allow letters? + * @param numbers only allow numbers? + * @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); + } + + /** + *

Creates a random string based on a variety of options, using + * supplied source of randomness.

+ * + *

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 {@code Integer.MAX_VALUE}. + * + *

If set is not {@code null}, characters between start and + * end are chosen.

+ * + *

This method accepts a user-supplied {@link Random} + * instance to use as a source of randomness. By seeding a single + * {@link Random} instance with a fixed seed and using it for each call, + * the same random sequence of strings can be generated repeatedly + * and predictably.

+ * + * @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 only allow letters? + * @param numbers only allow numbers? + * @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 Random 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 = Integer.MAX_VALUE; + } else { + end = 'z' + 1; + start = ' '; + } + } + } else { + if (end <= start) { + throw new IllegalArgumentException("Parameter end (" + end + ") must be greater than start (" + start + ")"); + } + } + + final char[] buffer = new char[count]; + final int gap = end - start; + + while (count-- != 0) { + char ch; + if (chars == null) { + ch = (char) (random.nextInt(gap) + start); + } else { + ch = chars[random.nextInt(gap) + start]; + } + if (letters && Character.isLetter(ch) + || numbers && Character.isDigit(ch) + || !letters && !numbers) { + if(ch >= 56320 && ch <= 57343) { + if(count == 0) { + count++; + } else { + // low surrogate, insert high surrogate after putting it in + buffer[count] = ch; + count--; + buffer[count] = (char) (55296 + random.nextInt(128)); + } + } else if(ch >= 55296 && ch <= 56191) { + if(count == 0) { + count++; + } else { + // high surrogate, insert low surrogate before putting it in + buffer[count] = (char) (56320 + random.nextInt(128)); + count--; + buffer[count] = ch; + } + } else if(ch >= 56192 && ch <= 56319) { + // private high surrogate, no effing clue, so skip it + count++; + } else { + buffer[count] = ch; + } + } else { + count++; + } + } + return new String(buffer); + } + + /** + *

Creates a random string whose length is the number of characters + * specified.

+ * + *

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.

+ * + * @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()); + } + + /** + *

Creates a random string whose length is the number of characters + * specified.

+ * + *

Characters will be chosen from the set of characters specified.

+ * + * @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. + */ +/** + *

Creates a random string whose length is the number of characters + * specified.

+ * + *

Characters will be chosen from the set of characters specified.

+ * + * @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 java.lang.String random(final int count, final char... chars) { + { + return org.apache.commons.lang3.RandomStringUtils.random(count, 0, /* NPEX_NULL_EXP */ + chars.length, false, false, chars, org.apache.commons.lang3.RandomStringUtils.RANDOM); + } +} + +} diff --git a/Java/commons-lang-RandomStringUtils_449/metadata.json b/Java/commons-lang-RandomStringUtils_449/metadata.json new file mode 100644 index 000000000..dd5de0438 --- /dev/null +++ b/Java/commons-lang-RandomStringUtils_449/metadata.json @@ -0,0 +1,21 @@ +{ + "language": "java", + "id": "commons-lang-RandomStringUtils_449", + "buggyPath": ".", + "referencePath": null, + "buildCommand": "mvn package -V -B -Denforcer.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true -Drat.skip=true -Dlicense.skip=true -Dfindbugs.skip=true -Dgpg.skip=true -Dskip.npm=true -Dskip.gulp=true -Dskip.bower=true -Drat.numUnapprovedLicenses=100 -DskipTests=true -DskipITs=true -Dtest=None -DfailIfNoTests=false", + "testCommand": "mvn test -V -B -Denforcer.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true -Drat.skip=true -Dlicense.skip=true -Dfindbugs.skip=true -Dgpg.skip=true -Dskip.npm=true -Dskip.gulp=true -Dskip.bower=true -Drat.numUnapprovedLicenses=100", + "categories": [ + "safety", + "npe" + ], + "npe": { + "filepath": "src/main/java/org/apache/commons/lang3/RandomStringUtils.java", + "line": 466, + "npe_method": "random", + "deref_field": "chars", + "npe_class": "RandomStringUtils", + "repo": "commons-lang", + "bug_id": "RandomStringUtils_449" + } +} diff --git a/Java/commons-lang-RandomStringUtils_449/npe.json b/Java/commons-lang-RandomStringUtils_449/npe.json new file mode 100644 index 000000000..074646038 --- /dev/null +++ b/Java/commons-lang-RandomStringUtils_449/npe.json @@ -0,0 +1,7 @@ +{ + "filepath": "src/main/java/org/apache/commons/lang3/RandomStringUtils.java", + "line": 466, + "npe_method": "random", + "deref_field": "chars", + "npe_class": "RandomStringUtils" +} \ No newline at end of file diff --git a/Java/commons-lang-Range_219/Dockerfile b/Java/commons-lang-Range_219/Dockerfile new file mode 100644 index 000000000..7b7fbe349 --- /dev/null +++ b/Java/commons-lang-Range_219/Dockerfile @@ -0,0 +1,18 @@ +FROM ghcr.io/kupl/starlab-benchmarks/java-base:commons-lang + +ENV TZ=Asia/Seoul + +COPY ./metadata.json . +COPY ./npe.json . +COPY ./buggy.java /tmp/buggy.java +RUN export BUGGY_PATH=$(cat metadata.json | jq -r ".npe.filepath") \ + && export BUGGY_LINE=$(cat metadata.json | jq -r ".npe.line") \ + && export BUGGY_MTHD=$(cat metadata.json | jq -r ".npe.npe_method") \ + && mv /tmp/buggy.java $BUGGY_PATH \ + && echo "[{\"filepath\": \"$BUGGY_PATH\", \"line\": $BUGGY_LINE, \"method_name\": \"$BUGGY_MTHD\"}]" | jq . > traces.json + +RUN git init . && git add -A + +RUN $(cat metadata.json | jq -r ".buildCommand") + +RUN $(cat metadata.json | jq -r ".testCommand"); if [ $? -eq 0 ]; then exit 1; fi diff --git a/Java/commons-lang-Range_219/buggy.java b/Java/commons-lang-Range_219/buggy.java new file mode 100644 index 000000000..cdb8ab125 --- /dev/null +++ b/Java/commons-lang-Range_219/buggy.java @@ -0,0 +1,496 @@ +/* + * 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; + +/** + *

An immutable range of objects from a minimum to maximum point inclusive.

+ * + *

The objects need to either be implementations of {@code Comparable} + * or you need to supply a {@code Comparator}.

+ * + *

#ThreadSafe# if the objects and comparator are thread-safe

+ * + * @since 3.0 + */ +public final class Range implements Serializable { + + /** + * Serialization version. + * @see java.io.Serializable + */ + private static final long serialVersionUID = 1L; + + /** + * The ordering scheme used in this range. + */ + private final Comparator comparator; + /** + * The minimum value in this range (inclusive). + */ + private final T minimum; + /** + * The maximum value in this range (inclusive). + */ + private final T maximum; + /** + * Cached output hashCode (class is immutable). + */ + private transient int hashCode; + /** + * Cached output toString (class is immutable). + */ + private transient String toString; + + /** + *

Obtains a range using the specified element as both the minimum + * and maximum in this range.

+ * + *

The range uses the natural ordering of the elements to determine where + * values lie in the range.

+ * + * @param 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 > Range is(final T element) { + return between(element, element, null); + } + + /** + *

Obtains a range using the specified element as both the minimum + * and maximum in this range.

+ * + *

The range uses the specified {@code Comparator} to determine where + * values lie in the range.

+ * + * @param 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 Range is(final T element, final Comparator comparator) { + return between(element, element, comparator); + } + + /** + *

Obtains a range with the specified minimum and maximum values (both inclusive).

+ * + *

The range uses the natural ordering of the elements to determine where + * values lie in the range.

+ * + *

The arguments may be passed in the order (min,max) or (max,min). + * The getMinimum and getMaximum methods will return the correct values.

+ * + * @param 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 > Range between(final T fromInclusive, final T toInclusive) { + return between(fromInclusive, toInclusive, null); + } + + /** + *

Obtains a range with the specified minimum and maximum values (both inclusive).

+ * + *

The range uses the specified {@code Comparator} to determine where + * values lie in the range.

+ * + *

The arguments may be passed in the order (min,max) or (max,min). + * The getMinimum and getMaximum methods will return the correct values.

+ * + * @param 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 Range between(final T fromInclusive, final T toInclusive, final Comparator comparator) { + return new Range(fromInclusive, toInclusive, comparator); + } + + /** + * 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 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; + } + } + + // Accessors + //-------------------------------------------------------------------- + + /** + *

Gets the minimum value in this range.

+ * + * @return the minimum value in this range, not null + */ + public T getMinimum() { + return minimum; + } + + /** + *

Gets the maximum value in this range.

+ * + * @return the maximum value in this range, not null + */ + public T getMaximum() { + return maximum; + } + + /** + *

Gets the comparator being used to determine if objects are within the range.

+ * + *

Natural ordering uses an internal comparator implementation, thus this + * method never returns null. See {@link #isNaturalOrdering()}.

+ * + * @return the comparator being used, not null + */ + public Comparator getComparator() { + return comparator; + } + + /** + *

Whether or not the Range is using the natural ordering of the elements.

+ * + *

Natural ordering uses an internal comparator implementation, thus this + * method is the only way to check if a null comparator was specified.

+ * + * @return true if using natural ordering + */ + public boolean isNaturalOrdering() { + return comparator == ComparableComparator.INSTANCE; + } + + // Element tests + //-------------------------------------------------------------------- + + /** + *

Checks whether the specified element occurs within this range.

+ * + * @param element the element to check for, null returns false + * @return true if the specified element occurs within this range + */ +// Element tests +// -------------------------------------------------------------------- +/** + *

Checks whether the specified element occurs within this range.

+ * + * @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) { + { + return (comparator.compare(/* NPEX_NULL_EXP */ + element, minimum) > (-1)) && (comparator.compare(element, maximum) < 1); + } +} + + /** + *

Checks whether this range is after the specified element.

+ * + * @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; + } + + /** + *

Checks whether this range starts with the specified element.

+ * + * @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; + } + + /** + *

Checks whether this range ends with the specified element.

+ * + * @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; + } + + /** + *

Checks whether this range is before the specified element.

+ * + * @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; + } + + /** + *

Checks where the specified element occurs relative to this range.

+ * + *

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.

+ * + * @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) { + if (element == null) { + // Comparable API says throw NPE on null + throw new NullPointerException("Element is null"); + } + if (isAfter(element)) { + return -1; + } else if (isBefore(element)) { + return 1; + } else { + return 0; + } + } + + // Range tests + //-------------------------------------------------------------------- + + /** + *

Checks whether this range contains all the elements of the specified range.

+ * + *

This method may fail if the ranges have two different comparators or element types.

+ * + * @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 otherRange) { + if (otherRange == null) { + return false; + } + return contains(otherRange.minimum) + && contains(otherRange.maximum); + } + + /** + *

Checks whether this range is completely after the specified range.

+ * + *

This method may fail if the ranges have two different comparators or element types.

+ * + * @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 otherRange) { + if (otherRange == null) { + return false; + } + return isAfter(otherRange.maximum); + } + + /** + *

Checks whether this range is overlapped by the specified range.

+ * + *

Two ranges overlap if there is at least one element in common.

+ * + *

This method may fail if the ranges have two different comparators or element types.

+ * + * @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 otherRange) { + if (otherRange == null) { + return false; + } + return otherRange.contains(minimum) + || otherRange.contains(maximum) + || contains(otherRange.minimum); + } + + /** + *

Checks whether this range is completely before the specified range.

+ * + *

This method may fail if the ranges have two different comparators or element types.

+ * + * @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 otherRange) { + if (otherRange == null) { + return false; + } + return isBefore(otherRange.minimum); + } + + /** + * 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 intersectionWith(final Range other) { + if (!this.isOverlappedBy(other)) { + throw new IllegalArgumentException(String.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()); + } + + // Basics + //-------------------------------------------------------------------- + + /** + *

Compares this range to another object to test if they are equal.

. + * + *

To be equal, the minimum and maximum values must be equal, which + * ignores any differences in the comparator.

+ * + * @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 range = (Range) obj; + return minimum.equals(range.minimum) && + maximum.equals(range.maximum); + } + } + + /** + *

Gets a suitable hash code for the range.

+ * + * @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; + } + + /** + *

Gets the range as a {@code String}.

+ * + *

The format of the String is '[min..max]'.

+ * + * @return the {@code String} representation of this range + */ + @Override + public String toString() { + if (toString == null) { + toString = "[" + minimum + ".." + maximum + "]"; + } + return toString; + } + + /** + *

Formats the receiver using the given format.

+ * + *

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]}.

+ * + * @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 String.format(format, minimum, maximum, comparator); + } + + //----------------------------------------------------------------------- + @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); + } + } + +} diff --git a/Java/commons-lang-Range_219/metadata.json b/Java/commons-lang-Range_219/metadata.json new file mode 100644 index 000000000..082ee8b4a --- /dev/null +++ b/Java/commons-lang-Range_219/metadata.json @@ -0,0 +1,21 @@ +{ + "language": "java", + "id": "commons-lang-Range_219", + "buggyPath": ".", + "referencePath": null, + "buildCommand": "mvn package -V -B -Denforcer.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true -Drat.skip=true -Dlicense.skip=true -Dfindbugs.skip=true -Dgpg.skip=true -Dskip.npm=true -Dskip.gulp=true -Dskip.bower=true -Drat.numUnapprovedLicenses=100 -DskipTests=true -DskipITs=true -Dtest=None -DfailIfNoTests=false", + "testCommand": "mvn test -V -B -Denforcer.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true -Drat.skip=true -Dlicense.skip=true -Dfindbugs.skip=true -Dgpg.skip=true -Dskip.npm=true -Dskip.gulp=true -Dskip.bower=true -Drat.numUnapprovedLicenses=100", + "categories": [ + "safety", + "npe" + ], + "npe": { + "filepath": "src/main/java/org/apache/commons/lang3/Range.java", + "line": 230, + "npe_method": "contains", + "deref_field": "element", + "npe_class": "Range", + "repo": "commons-lang", + "bug_id": "Range_219" + } +} diff --git a/Java/commons-lang-Range_219/npe.json b/Java/commons-lang-Range_219/npe.json new file mode 100644 index 000000000..fb8ce7a4e --- /dev/null +++ b/Java/commons-lang-Range_219/npe.json @@ -0,0 +1,7 @@ +{ + "filepath": "src/main/java/org/apache/commons/lang3/Range.java", + "line": 230, + "npe_method": "contains", + "deref_field": "element", + "npe_class": "Range" +} \ No newline at end of file diff --git a/Java/commons-lang-Range_232/Dockerfile b/Java/commons-lang-Range_232/Dockerfile new file mode 100644 index 000000000..7b7fbe349 --- /dev/null +++ b/Java/commons-lang-Range_232/Dockerfile @@ -0,0 +1,18 @@ +FROM ghcr.io/kupl/starlab-benchmarks/java-base:commons-lang + +ENV TZ=Asia/Seoul + +COPY ./metadata.json . +COPY ./npe.json . +COPY ./buggy.java /tmp/buggy.java +RUN export BUGGY_PATH=$(cat metadata.json | jq -r ".npe.filepath") \ + && export BUGGY_LINE=$(cat metadata.json | jq -r ".npe.line") \ + && export BUGGY_MTHD=$(cat metadata.json | jq -r ".npe.npe_method") \ + && mv /tmp/buggy.java $BUGGY_PATH \ + && echo "[{\"filepath\": \"$BUGGY_PATH\", \"line\": $BUGGY_LINE, \"method_name\": \"$BUGGY_MTHD\"}]" | jq . > traces.json + +RUN git init . && git add -A + +RUN $(cat metadata.json | jq -r ".buildCommand") + +RUN $(cat metadata.json | jq -r ".testCommand"); if [ $? -eq 0 ]; then exit 1; fi diff --git a/Java/commons-lang-Range_232/buggy.java b/Java/commons-lang-Range_232/buggy.java new file mode 100644 index 000000000..bfb1a653d --- /dev/null +++ b/Java/commons-lang-Range_232/buggy.java @@ -0,0 +1,494 @@ +/* + * 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; + +/** + *

An immutable range of objects from a minimum to maximum point inclusive.

+ * + *

The objects need to either be implementations of {@code Comparable} + * or you need to supply a {@code Comparator}.

+ * + *

#ThreadSafe# if the objects and comparator are thread-safe

+ * + * @since 3.0 + */ +public final class Range implements Serializable { + + /** + * Serialization version. + * @see java.io.Serializable + */ + private static final long serialVersionUID = 1L; + + /** + * The ordering scheme used in this range. + */ + private final Comparator comparator; + /** + * The minimum value in this range (inclusive). + */ + private final T minimum; + /** + * The maximum value in this range (inclusive). + */ + private final T maximum; + /** + * Cached output hashCode (class is immutable). + */ + private transient int hashCode; + /** + * Cached output toString (class is immutable). + */ + private transient String toString; + + /** + *

Obtains a range using the specified element as both the minimum + * and maximum in this range.

+ * + *

The range uses the natural ordering of the elements to determine where + * values lie in the range.

+ * + * @param 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 > Range is(final T element) { + return between(element, element, null); + } + + /** + *

Obtains a range using the specified element as both the minimum + * and maximum in this range.

+ * + *

The range uses the specified {@code Comparator} to determine where + * values lie in the range.

+ * + * @param 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 Range is(final T element, final Comparator comparator) { + return between(element, element, comparator); + } + + /** + *

Obtains a range with the specified minimum and maximum values (both inclusive).

+ * + *

The range uses the natural ordering of the elements to determine where + * values lie in the range.

+ * + *

The arguments may be passed in the order (min,max) or (max,min). + * The getMinimum and getMaximum methods will return the correct values.

+ * + * @param 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 > Range between(final T fromInclusive, final T toInclusive) { + return between(fromInclusive, toInclusive, null); + } + + /** + *

Obtains a range with the specified minimum and maximum values (both inclusive).

+ * + *

The range uses the specified {@code Comparator} to determine where + * values lie in the range.

+ * + *

The arguments may be passed in the order (min,max) or (max,min). + * The getMinimum and getMaximum methods will return the correct values.

+ * + * @param 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 Range between(final T fromInclusive, final T toInclusive, final Comparator comparator) { + return new Range(fromInclusive, toInclusive, comparator); + } + + /** + * 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 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; + } + } + + // Accessors + //-------------------------------------------------------------------- + + /** + *

Gets the minimum value in this range.

+ * + * @return the minimum value in this range, not null + */ + public T getMinimum() { + return minimum; + } + + /** + *

Gets the maximum value in this range.

+ * + * @return the maximum value in this range, not null + */ + public T getMaximum() { + return maximum; + } + + /** + *

Gets the comparator being used to determine if objects are within the range.

+ * + *

Natural ordering uses an internal comparator implementation, thus this + * method never returns null. See {@link #isNaturalOrdering()}.

+ * + * @return the comparator being used, not null + */ + public Comparator getComparator() { + return comparator; + } + + /** + *

Whether or not the Range is using the natural ordering of the elements.

+ * + *

Natural ordering uses an internal comparator implementation, thus this + * method is the only way to check if a null comparator was specified.

+ * + * @return true if using natural ordering + */ + public boolean isNaturalOrdering() { + return comparator == ComparableComparator.INSTANCE; + } + + // Element tests + //-------------------------------------------------------------------- + + /** + *

Checks whether the specified element occurs within this range.

+ * + * @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; + } + + /** + *

Checks whether this range is after the specified element.

+ * + * @param element the element to check for, null returns false + * @return true if this range is entirely after the specified element + */ +/** + *

Checks whether this range is after the specified element.

+ * + * @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) { + { + return comparator.compare(/* NPEX_NULL_EXP */ + element, minimum) < 0; + } +} + + /** + *

Checks whether this range starts with the specified element.

+ * + * @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; + } + + /** + *

Checks whether this range ends with the specified element.

+ * + * @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; + } + + /** + *

Checks whether this range is before the specified element.

+ * + * @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; + } + + /** + *

Checks where the specified element occurs relative to this range.

+ * + *

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.

+ * + * @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) { + if (element == null) { + // Comparable API says throw NPE on null + throw new NullPointerException("Element is null"); + } + if (isAfter(element)) { + return -1; + } else if (isBefore(element)) { + return 1; + } else { + return 0; + } + } + + // Range tests + //-------------------------------------------------------------------- + + /** + *

Checks whether this range contains all the elements of the specified range.

+ * + *

This method may fail if the ranges have two different comparators or element types.

+ * + * @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 otherRange) { + if (otherRange == null) { + return false; + } + return contains(otherRange.minimum) + && contains(otherRange.maximum); + } + + /** + *

Checks whether this range is completely after the specified range.

+ * + *

This method may fail if the ranges have two different comparators or element types.

+ * + * @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 otherRange) { + if (otherRange == null) { + return false; + } + return isAfter(otherRange.maximum); + } + + /** + *

Checks whether this range is overlapped by the specified range.

+ * + *

Two ranges overlap if there is at least one element in common.

+ * + *

This method may fail if the ranges have two different comparators or element types.

+ * + * @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 otherRange) { + if (otherRange == null) { + return false; + } + return otherRange.contains(minimum) + || otherRange.contains(maximum) + || contains(otherRange.minimum); + } + + /** + *

Checks whether this range is completely before the specified range.

+ * + *

This method may fail if the ranges have two different comparators or element types.

+ * + * @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 otherRange) { + if (otherRange == null) { + return false; + } + return isBefore(otherRange.minimum); + } + + /** + * 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 intersectionWith(final Range other) { + if (!this.isOverlappedBy(other)) { + throw new IllegalArgumentException(String.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()); + } + + // Basics + //-------------------------------------------------------------------- + + /** + *

Compares this range to another object to test if they are equal.

. + * + *

To be equal, the minimum and maximum values must be equal, which + * ignores any differences in the comparator.

+ * + * @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 range = (Range) obj; + return minimum.equals(range.minimum) && + maximum.equals(range.maximum); + } + } + + /** + *

Gets a suitable hash code for the range.

+ * + * @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; + } + + /** + *

Gets the range as a {@code String}.

+ * + *

The format of the String is '[min..max]'.

+ * + * @return the {@code String} representation of this range + */ + @Override + public String toString() { + if (toString == null) { + toString = "[" + minimum + ".." + maximum + "]"; + } + return toString; + } + + /** + *

Formats the receiver using the given format.

+ * + *

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]}.

+ * + * @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 String.format(format, minimum, maximum, comparator); + } + + //----------------------------------------------------------------------- + @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); + } + } + +} diff --git a/Java/commons-lang-Range_232/metadata.json b/Java/commons-lang-Range_232/metadata.json new file mode 100644 index 000000000..751f099a7 --- /dev/null +++ b/Java/commons-lang-Range_232/metadata.json @@ -0,0 +1,21 @@ +{ + "language": "java", + "id": "commons-lang-Range_232", + "buggyPath": ".", + "referencePath": null, + "buildCommand": "mvn package -V -B -Denforcer.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true -Drat.skip=true -Dlicense.skip=true -Dfindbugs.skip=true -Dgpg.skip=true -Dskip.npm=true -Dskip.gulp=true -Dskip.bower=true -Drat.numUnapprovedLicenses=100 -DskipTests=true -DskipITs=true -Dtest=None -DfailIfNoTests=false", + "testCommand": "mvn test -V -B -Denforcer.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true -Drat.skip=true -Dlicense.skip=true -Dfindbugs.skip=true -Dgpg.skip=true -Dskip.npm=true -Dskip.gulp=true -Dskip.bower=true -Drat.numUnapprovedLicenses=100", + "categories": [ + "safety", + "npe" + ], + "npe": { + "filepath": "src/main/java/org/apache/commons/lang3/Range.java", + "line": 241, + "npe_method": "isAfter", + "deref_field": "element", + "npe_class": "Range", + "repo": "commons-lang", + "bug_id": "Range_232" + } +} diff --git a/Java/commons-lang-Range_232/npe.json b/Java/commons-lang-Range_232/npe.json new file mode 100644 index 000000000..d982c4459 --- /dev/null +++ b/Java/commons-lang-Range_232/npe.json @@ -0,0 +1,7 @@ +{ + "filepath": "src/main/java/org/apache/commons/lang3/Range.java", + "line": 241, + "npe_method": "isAfter", + "deref_field": "element", + "npe_class": "Range" +} \ No newline at end of file diff --git a/Java/commons-lang-Range_245/Dockerfile b/Java/commons-lang-Range_245/Dockerfile new file mode 100644 index 000000000..7b7fbe349 --- /dev/null +++ b/Java/commons-lang-Range_245/Dockerfile @@ -0,0 +1,18 @@ +FROM ghcr.io/kupl/starlab-benchmarks/java-base:commons-lang + +ENV TZ=Asia/Seoul + +COPY ./metadata.json . +COPY ./npe.json . +COPY ./buggy.java /tmp/buggy.java +RUN export BUGGY_PATH=$(cat metadata.json | jq -r ".npe.filepath") \ + && export BUGGY_LINE=$(cat metadata.json | jq -r ".npe.line") \ + && export BUGGY_MTHD=$(cat metadata.json | jq -r ".npe.npe_method") \ + && mv /tmp/buggy.java $BUGGY_PATH \ + && echo "[{\"filepath\": \"$BUGGY_PATH\", \"line\": $BUGGY_LINE, \"method_name\": \"$BUGGY_MTHD\"}]" | jq . > traces.json + +RUN git init . && git add -A + +RUN $(cat metadata.json | jq -r ".buildCommand") + +RUN $(cat metadata.json | jq -r ".testCommand"); if [ $? -eq 0 ]; then exit 1; fi diff --git a/Java/commons-lang-Range_245/buggy.java b/Java/commons-lang-Range_245/buggy.java new file mode 100644 index 000000000..d995bdfaf --- /dev/null +++ b/Java/commons-lang-Range_245/buggy.java @@ -0,0 +1,494 @@ +/* + * 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; + +/** + *

An immutable range of objects from a minimum to maximum point inclusive.

+ * + *

The objects need to either be implementations of {@code Comparable} + * or you need to supply a {@code Comparator}.

+ * + *

#ThreadSafe# if the objects and comparator are thread-safe

+ * + * @since 3.0 + */ +public final class Range implements Serializable { + + /** + * Serialization version. + * @see java.io.Serializable + */ + private static final long serialVersionUID = 1L; + + /** + * The ordering scheme used in this range. + */ + private final Comparator comparator; + /** + * The minimum value in this range (inclusive). + */ + private final T minimum; + /** + * The maximum value in this range (inclusive). + */ + private final T maximum; + /** + * Cached output hashCode (class is immutable). + */ + private transient int hashCode; + /** + * Cached output toString (class is immutable). + */ + private transient String toString; + + /** + *

Obtains a range using the specified element as both the minimum + * and maximum in this range.

+ * + *

The range uses the natural ordering of the elements to determine where + * values lie in the range.

+ * + * @param 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 > Range is(final T element) { + return between(element, element, null); + } + + /** + *

Obtains a range using the specified element as both the minimum + * and maximum in this range.

+ * + *

The range uses the specified {@code Comparator} to determine where + * values lie in the range.

+ * + * @param 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 Range is(final T element, final Comparator comparator) { + return between(element, element, comparator); + } + + /** + *

Obtains a range with the specified minimum and maximum values (both inclusive).

+ * + *

The range uses the natural ordering of the elements to determine where + * values lie in the range.

+ * + *

The arguments may be passed in the order (min,max) or (max,min). + * The getMinimum and getMaximum methods will return the correct values.

+ * + * @param 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 > Range between(final T fromInclusive, final T toInclusive) { + return between(fromInclusive, toInclusive, null); + } + + /** + *

Obtains a range with the specified minimum and maximum values (both inclusive).

+ * + *

The range uses the specified {@code Comparator} to determine where + * values lie in the range.

+ * + *

The arguments may be passed in the order (min,max) or (max,min). + * The getMinimum and getMaximum methods will return the correct values.

+ * + * @param 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 Range between(final T fromInclusive, final T toInclusive, final Comparator comparator) { + return new Range(fromInclusive, toInclusive, comparator); + } + + /** + * 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 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; + } + } + + // Accessors + //-------------------------------------------------------------------- + + /** + *

Gets the minimum value in this range.

+ * + * @return the minimum value in this range, not null + */ + public T getMinimum() { + return minimum; + } + + /** + *

Gets the maximum value in this range.

+ * + * @return the maximum value in this range, not null + */ + public T getMaximum() { + return maximum; + } + + /** + *

Gets the comparator being used to determine if objects are within the range.

+ * + *

Natural ordering uses an internal comparator implementation, thus this + * method never returns null. See {@link #isNaturalOrdering()}.

+ * + * @return the comparator being used, not null + */ + public Comparator getComparator() { + return comparator; + } + + /** + *

Whether or not the Range is using the natural ordering of the elements.

+ * + *

Natural ordering uses an internal comparator implementation, thus this + * method is the only way to check if a null comparator was specified.

+ * + * @return true if using natural ordering + */ + public boolean isNaturalOrdering() { + return comparator == ComparableComparator.INSTANCE; + } + + // Element tests + //-------------------------------------------------------------------- + + /** + *

Checks whether the specified element occurs within this range.

+ * + * @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; + } + + /** + *

Checks whether this range is after the specified element.

+ * + * @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; + } + + /** + *

Checks whether this range starts with the specified element.

+ * + * @param element the element to check for, null returns false + * @return true if the specified element occurs within this range + */ +/** + *

Checks whether this range starts with the specified element.

+ * + * @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) { + { + return comparator.compare(/* NPEX_NULL_EXP */ + element, minimum) == 0; + } +} + + /** + *

Checks whether this range ends with the specified element.

+ * + * @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; + } + + /** + *

Checks whether this range is before the specified element.

+ * + * @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; + } + + /** + *

Checks where the specified element occurs relative to this range.

+ * + *

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.

+ * + * @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) { + if (element == null) { + // Comparable API says throw NPE on null + throw new NullPointerException("Element is null"); + } + if (isAfter(element)) { + return -1; + } else if (isBefore(element)) { + return 1; + } else { + return 0; + } + } + + // Range tests + //-------------------------------------------------------------------- + + /** + *

Checks whether this range contains all the elements of the specified range.

+ * + *

This method may fail if the ranges have two different comparators or element types.

+ * + * @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 otherRange) { + if (otherRange == null) { + return false; + } + return contains(otherRange.minimum) + && contains(otherRange.maximum); + } + + /** + *

Checks whether this range is completely after the specified range.

+ * + *

This method may fail if the ranges have two different comparators or element types.

+ * + * @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 otherRange) { + if (otherRange == null) { + return false; + } + return isAfter(otherRange.maximum); + } + + /** + *

Checks whether this range is overlapped by the specified range.

+ * + *

Two ranges overlap if there is at least one element in common.

+ * + *

This method may fail if the ranges have two different comparators or element types.

+ * + * @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 otherRange) { + if (otherRange == null) { + return false; + } + return otherRange.contains(minimum) + || otherRange.contains(maximum) + || contains(otherRange.minimum); + } + + /** + *

Checks whether this range is completely before the specified range.

+ * + *

This method may fail if the ranges have two different comparators or element types.

+ * + * @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 otherRange) { + if (otherRange == null) { + return false; + } + return isBefore(otherRange.minimum); + } + + /** + * 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 intersectionWith(final Range other) { + if (!this.isOverlappedBy(other)) { + throw new IllegalArgumentException(String.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()); + } + + // Basics + //-------------------------------------------------------------------- + + /** + *

Compares this range to another object to test if they are equal.

. + * + *

To be equal, the minimum and maximum values must be equal, which + * ignores any differences in the comparator.

+ * + * @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 range = (Range) obj; + return minimum.equals(range.minimum) && + maximum.equals(range.maximum); + } + } + + /** + *

Gets a suitable hash code for the range.

+ * + * @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; + } + + /** + *

Gets the range as a {@code String}.

+ * + *

The format of the String is '[min..max]'.

+ * + * @return the {@code String} representation of this range + */ + @Override + public String toString() { + if (toString == null) { + toString = "[" + minimum + ".." + maximum + "]"; + } + return toString; + } + + /** + *

Formats the receiver using the given format.

+ * + *

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]}.

+ * + * @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 String.format(format, minimum, maximum, comparator); + } + + //----------------------------------------------------------------------- + @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); + } + } + +} diff --git a/Java/commons-lang-Range_245/metadata.json b/Java/commons-lang-Range_245/metadata.json new file mode 100644 index 000000000..92d64d8fe --- /dev/null +++ b/Java/commons-lang-Range_245/metadata.json @@ -0,0 +1,21 @@ +{ + "language": "java", + "id": "commons-lang-Range_245", + "buggyPath": ".", + "referencePath": null, + "buildCommand": "mvn package -V -B -Denforcer.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true -Drat.skip=true -Dlicense.skip=true -Dfindbugs.skip=true -Dgpg.skip=true -Dskip.npm=true -Dskip.gulp=true -Dskip.bower=true -Drat.numUnapprovedLicenses=100 -DskipTests=true -DskipITs=true -Dtest=None -DfailIfNoTests=false", + "testCommand": "mvn test -V -B -Denforcer.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true -Drat.skip=true -Dlicense.skip=true -Dfindbugs.skip=true -Dgpg.skip=true -Dskip.npm=true -Dskip.gulp=true -Dskip.bower=true -Drat.numUnapprovedLicenses=100", + "categories": [ + "safety", + "npe" + ], + "npe": { + "filepath": "src/main/java/org/apache/commons/lang3/Range.java", + "line": 254, + "npe_method": "isStartedBy", + "deref_field": "element", + "npe_class": "Range", + "repo": "commons-lang", + "bug_id": "Range_245" + } +} diff --git a/Java/commons-lang-Range_245/npe.json b/Java/commons-lang-Range_245/npe.json new file mode 100644 index 000000000..d8b8e6fc1 --- /dev/null +++ b/Java/commons-lang-Range_245/npe.json @@ -0,0 +1,7 @@ +{ + "filepath": "src/main/java/org/apache/commons/lang3/Range.java", + "line": 254, + "npe_method": "isStartedBy", + "deref_field": "element", + "npe_class": "Range" +} \ No newline at end of file diff --git a/Java/commons-lang-Range_258/Dockerfile b/Java/commons-lang-Range_258/Dockerfile new file mode 100644 index 000000000..7b7fbe349 --- /dev/null +++ b/Java/commons-lang-Range_258/Dockerfile @@ -0,0 +1,18 @@ +FROM ghcr.io/kupl/starlab-benchmarks/java-base:commons-lang + +ENV TZ=Asia/Seoul + +COPY ./metadata.json . +COPY ./npe.json . +COPY ./buggy.java /tmp/buggy.java +RUN export BUGGY_PATH=$(cat metadata.json | jq -r ".npe.filepath") \ + && export BUGGY_LINE=$(cat metadata.json | jq -r ".npe.line") \ + && export BUGGY_MTHD=$(cat metadata.json | jq -r ".npe.npe_method") \ + && mv /tmp/buggy.java $BUGGY_PATH \ + && echo "[{\"filepath\": \"$BUGGY_PATH\", \"line\": $BUGGY_LINE, \"method_name\": \"$BUGGY_MTHD\"}]" | jq . > traces.json + +RUN git init . && git add -A + +RUN $(cat metadata.json | jq -r ".buildCommand") + +RUN $(cat metadata.json | jq -r ".testCommand"); if [ $? -eq 0 ]; then exit 1; fi diff --git a/Java/commons-lang-Range_258/buggy.java b/Java/commons-lang-Range_258/buggy.java new file mode 100644 index 000000000..82700f250 --- /dev/null +++ b/Java/commons-lang-Range_258/buggy.java @@ -0,0 +1,494 @@ +/* + * 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; + +/** + *

An immutable range of objects from a minimum to maximum point inclusive.

+ * + *

The objects need to either be implementations of {@code Comparable} + * or you need to supply a {@code Comparator}.

+ * + *

#ThreadSafe# if the objects and comparator are thread-safe

+ * + * @since 3.0 + */ +public final class Range implements Serializable { + + /** + * Serialization version. + * @see java.io.Serializable + */ + private static final long serialVersionUID = 1L; + + /** + * The ordering scheme used in this range. + */ + private final Comparator comparator; + /** + * The minimum value in this range (inclusive). + */ + private final T minimum; + /** + * The maximum value in this range (inclusive). + */ + private final T maximum; + /** + * Cached output hashCode (class is immutable). + */ + private transient int hashCode; + /** + * Cached output toString (class is immutable). + */ + private transient String toString; + + /** + *

Obtains a range using the specified element as both the minimum + * and maximum in this range.

+ * + *

The range uses the natural ordering of the elements to determine where + * values lie in the range.

+ * + * @param 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 > Range is(final T element) { + return between(element, element, null); + } + + /** + *

Obtains a range using the specified element as both the minimum + * and maximum in this range.

+ * + *

The range uses the specified {@code Comparator} to determine where + * values lie in the range.

+ * + * @param 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 Range is(final T element, final Comparator comparator) { + return between(element, element, comparator); + } + + /** + *

Obtains a range with the specified minimum and maximum values (both inclusive).

+ * + *

The range uses the natural ordering of the elements to determine where + * values lie in the range.

+ * + *

The arguments may be passed in the order (min,max) or (max,min). + * The getMinimum and getMaximum methods will return the correct values.

+ * + * @param 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 > Range between(final T fromInclusive, final T toInclusive) { + return between(fromInclusive, toInclusive, null); + } + + /** + *

Obtains a range with the specified minimum and maximum values (both inclusive).

+ * + *

The range uses the specified {@code Comparator} to determine where + * values lie in the range.

+ * + *

The arguments may be passed in the order (min,max) or (max,min). + * The getMinimum and getMaximum methods will return the correct values.

+ * + * @param 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 Range between(final T fromInclusive, final T toInclusive, final Comparator comparator) { + return new Range(fromInclusive, toInclusive, comparator); + } + + /** + * 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 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; + } + } + + // Accessors + //-------------------------------------------------------------------- + + /** + *

Gets the minimum value in this range.

+ * + * @return the minimum value in this range, not null + */ + public T getMinimum() { + return minimum; + } + + /** + *

Gets the maximum value in this range.

+ * + * @return the maximum value in this range, not null + */ + public T getMaximum() { + return maximum; + } + + /** + *

Gets the comparator being used to determine if objects are within the range.

+ * + *

Natural ordering uses an internal comparator implementation, thus this + * method never returns null. See {@link #isNaturalOrdering()}.

+ * + * @return the comparator being used, not null + */ + public Comparator getComparator() { + return comparator; + } + + /** + *

Whether or not the Range is using the natural ordering of the elements.

+ * + *

Natural ordering uses an internal comparator implementation, thus this + * method is the only way to check if a null comparator was specified.

+ * + * @return true if using natural ordering + */ + public boolean isNaturalOrdering() { + return comparator == ComparableComparator.INSTANCE; + } + + // Element tests + //-------------------------------------------------------------------- + + /** + *

Checks whether the specified element occurs within this range.

+ * + * @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; + } + + /** + *

Checks whether this range is after the specified element.

+ * + * @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; + } + + /** + *

Checks whether this range starts with the specified element.

+ * + * @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; + } + + /** + *

Checks whether this range ends with the specified element.

+ * + * @param element the element to check for, null returns false + * @return true if the specified element occurs within this range + */ +/** + *

Checks whether this range ends with the specified element.

+ * + * @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) { + { + return comparator.compare(/* NPEX_NULL_EXP */ + element, maximum) == 0; + } +} + + /** + *

Checks whether this range is before the specified element.

+ * + * @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; + } + + /** + *

Checks where the specified element occurs relative to this range.

+ * + *

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.

+ * + * @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) { + if (element == null) { + // Comparable API says throw NPE on null + throw new NullPointerException("Element is null"); + } + if (isAfter(element)) { + return -1; + } else if (isBefore(element)) { + return 1; + } else { + return 0; + } + } + + // Range tests + //-------------------------------------------------------------------- + + /** + *

Checks whether this range contains all the elements of the specified range.

+ * + *

This method may fail if the ranges have two different comparators or element types.

+ * + * @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 otherRange) { + if (otherRange == null) { + return false; + } + return contains(otherRange.minimum) + && contains(otherRange.maximum); + } + + /** + *

Checks whether this range is completely after the specified range.

+ * + *

This method may fail if the ranges have two different comparators or element types.

+ * + * @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 otherRange) { + if (otherRange == null) { + return false; + } + return isAfter(otherRange.maximum); + } + + /** + *

Checks whether this range is overlapped by the specified range.

+ * + *

Two ranges overlap if there is at least one element in common.

+ * + *

This method may fail if the ranges have two different comparators or element types.

+ * + * @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 otherRange) { + if (otherRange == null) { + return false; + } + return otherRange.contains(minimum) + || otherRange.contains(maximum) + || contains(otherRange.minimum); + } + + /** + *

Checks whether this range is completely before the specified range.

+ * + *

This method may fail if the ranges have two different comparators or element types.

+ * + * @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 otherRange) { + if (otherRange == null) { + return false; + } + return isBefore(otherRange.minimum); + } + + /** + * 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 intersectionWith(final Range other) { + if (!this.isOverlappedBy(other)) { + throw new IllegalArgumentException(String.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()); + } + + // Basics + //-------------------------------------------------------------------- + + /** + *

Compares this range to another object to test if they are equal.

. + * + *

To be equal, the minimum and maximum values must be equal, which + * ignores any differences in the comparator.

+ * + * @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 range = (Range) obj; + return minimum.equals(range.minimum) && + maximum.equals(range.maximum); + } + } + + /** + *

Gets a suitable hash code for the range.

+ * + * @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; + } + + /** + *

Gets the range as a {@code String}.

+ * + *

The format of the String is '[min..max]'.

+ * + * @return the {@code String} representation of this range + */ + @Override + public String toString() { + if (toString == null) { + toString = "[" + minimum + ".." + maximum + "]"; + } + return toString; + } + + /** + *

Formats the receiver using the given format.

+ * + *

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]}.

+ * + * @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 String.format(format, minimum, maximum, comparator); + } + + //----------------------------------------------------------------------- + @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); + } + } + +} diff --git a/Java/commons-lang-Range_258/metadata.json b/Java/commons-lang-Range_258/metadata.json new file mode 100644 index 000000000..e60087a95 --- /dev/null +++ b/Java/commons-lang-Range_258/metadata.json @@ -0,0 +1,21 @@ +{ + "language": "java", + "id": "commons-lang-Range_258", + "buggyPath": ".", + "referencePath": null, + "buildCommand": "mvn package -V -B -Denforcer.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true -Drat.skip=true -Dlicense.skip=true -Dfindbugs.skip=true -Dgpg.skip=true -Dskip.npm=true -Dskip.gulp=true -Dskip.bower=true -Drat.numUnapprovedLicenses=100 -DskipTests=true -DskipITs=true -Dtest=None -DfailIfNoTests=false", + "testCommand": "mvn test -V -B -Denforcer.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true -Drat.skip=true -Dlicense.skip=true -Dfindbugs.skip=true -Dgpg.skip=true -Dskip.npm=true -Dskip.gulp=true -Dskip.bower=true -Drat.numUnapprovedLicenses=100", + "categories": [ + "safety", + "npe" + ], + "npe": { + "filepath": "src/main/java/org/apache/commons/lang3/Range.java", + "line": 267, + "npe_method": "isEndedBy", + "deref_field": "element", + "npe_class": "Range", + "repo": "commons-lang", + "bug_id": "Range_258" + } +} diff --git a/Java/commons-lang-Range_258/npe.json b/Java/commons-lang-Range_258/npe.json new file mode 100644 index 000000000..ab3bbc51e --- /dev/null +++ b/Java/commons-lang-Range_258/npe.json @@ -0,0 +1,7 @@ +{ + "filepath": "src/main/java/org/apache/commons/lang3/Range.java", + "line": 267, + "npe_method": "isEndedBy", + "deref_field": "element", + "npe_class": "Range" +} \ No newline at end of file diff --git a/Java/commons-lang-Range_271/Dockerfile b/Java/commons-lang-Range_271/Dockerfile new file mode 100644 index 000000000..7b7fbe349 --- /dev/null +++ b/Java/commons-lang-Range_271/Dockerfile @@ -0,0 +1,18 @@ +FROM ghcr.io/kupl/starlab-benchmarks/java-base:commons-lang + +ENV TZ=Asia/Seoul + +COPY ./metadata.json . +COPY ./npe.json . +COPY ./buggy.java /tmp/buggy.java +RUN export BUGGY_PATH=$(cat metadata.json | jq -r ".npe.filepath") \ + && export BUGGY_LINE=$(cat metadata.json | jq -r ".npe.line") \ + && export BUGGY_MTHD=$(cat metadata.json | jq -r ".npe.npe_method") \ + && mv /tmp/buggy.java $BUGGY_PATH \ + && echo "[{\"filepath\": \"$BUGGY_PATH\", \"line\": $BUGGY_LINE, \"method_name\": \"$BUGGY_MTHD\"}]" | jq . > traces.json + +RUN git init . && git add -A + +RUN $(cat metadata.json | jq -r ".buildCommand") + +RUN $(cat metadata.json | jq -r ".testCommand"); if [ $? -eq 0 ]; then exit 1; fi diff --git a/Java/commons-lang-Range_271/buggy.java b/Java/commons-lang-Range_271/buggy.java new file mode 100644 index 000000000..64758f251 --- /dev/null +++ b/Java/commons-lang-Range_271/buggy.java @@ -0,0 +1,494 @@ +/* + * 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; + +/** + *

An immutable range of objects from a minimum to maximum point inclusive.

+ * + *

The objects need to either be implementations of {@code Comparable} + * or you need to supply a {@code Comparator}.

+ * + *

#ThreadSafe# if the objects and comparator are thread-safe

+ * + * @since 3.0 + */ +public final class Range implements Serializable { + + /** + * Serialization version. + * @see java.io.Serializable + */ + private static final long serialVersionUID = 1L; + + /** + * The ordering scheme used in this range. + */ + private final Comparator comparator; + /** + * The minimum value in this range (inclusive). + */ + private final T minimum; + /** + * The maximum value in this range (inclusive). + */ + private final T maximum; + /** + * Cached output hashCode (class is immutable). + */ + private transient int hashCode; + /** + * Cached output toString (class is immutable). + */ + private transient String toString; + + /** + *

Obtains a range using the specified element as both the minimum + * and maximum in this range.

+ * + *

The range uses the natural ordering of the elements to determine where + * values lie in the range.

+ * + * @param 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 > Range is(final T element) { + return between(element, element, null); + } + + /** + *

Obtains a range using the specified element as both the minimum + * and maximum in this range.

+ * + *

The range uses the specified {@code Comparator} to determine where + * values lie in the range.

+ * + * @param 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 Range is(final T element, final Comparator comparator) { + return between(element, element, comparator); + } + + /** + *

Obtains a range with the specified minimum and maximum values (both inclusive).

+ * + *

The range uses the natural ordering of the elements to determine where + * values lie in the range.

+ * + *

The arguments may be passed in the order (min,max) or (max,min). + * The getMinimum and getMaximum methods will return the correct values.

+ * + * @param 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 > Range between(final T fromInclusive, final T toInclusive) { + return between(fromInclusive, toInclusive, null); + } + + /** + *

Obtains a range with the specified minimum and maximum values (both inclusive).

+ * + *

The range uses the specified {@code Comparator} to determine where + * values lie in the range.

+ * + *

The arguments may be passed in the order (min,max) or (max,min). + * The getMinimum and getMaximum methods will return the correct values.

+ * + * @param 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 Range between(final T fromInclusive, final T toInclusive, final Comparator comparator) { + return new Range(fromInclusive, toInclusive, comparator); + } + + /** + * 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 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; + } + } + + // Accessors + //-------------------------------------------------------------------- + + /** + *

Gets the minimum value in this range.

+ * + * @return the minimum value in this range, not null + */ + public T getMinimum() { + return minimum; + } + + /** + *

Gets the maximum value in this range.

+ * + * @return the maximum value in this range, not null + */ + public T getMaximum() { + return maximum; + } + + /** + *

Gets the comparator being used to determine if objects are within the range.

+ * + *

Natural ordering uses an internal comparator implementation, thus this + * method never returns null. See {@link #isNaturalOrdering()}.

+ * + * @return the comparator being used, not null + */ + public Comparator getComparator() { + return comparator; + } + + /** + *

Whether or not the Range is using the natural ordering of the elements.

+ * + *

Natural ordering uses an internal comparator implementation, thus this + * method is the only way to check if a null comparator was specified.

+ * + * @return true if using natural ordering + */ + public boolean isNaturalOrdering() { + return comparator == ComparableComparator.INSTANCE; + } + + // Element tests + //-------------------------------------------------------------------- + + /** + *

Checks whether the specified element occurs within this range.

+ * + * @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; + } + + /** + *

Checks whether this range is after the specified element.

+ * + * @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; + } + + /** + *

Checks whether this range starts with the specified element.

+ * + * @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; + } + + /** + *

Checks whether this range ends with the specified element.

+ * + * @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; + } + + /** + *

Checks whether this range is before the specified element.

+ * + * @param element the element to check for, null returns false + * @return true if this range is entirely before the specified element + */ +/** + *

Checks whether this range is before the specified element.

+ * + * @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) { + { + return comparator.compare(/* NPEX_NULL_EXP */ + element, maximum) > 0; + } +} + + /** + *

Checks where the specified element occurs relative to this range.

+ * + *

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.

+ * + * @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) { + if (element == null) { + // Comparable API says throw NPE on null + throw new NullPointerException("Element is null"); + } + if (isAfter(element)) { + return -1; + } else if (isBefore(element)) { + return 1; + } else { + return 0; + } + } + + // Range tests + //-------------------------------------------------------------------- + + /** + *

Checks whether this range contains all the elements of the specified range.

+ * + *

This method may fail if the ranges have two different comparators or element types.

+ * + * @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 otherRange) { + if (otherRange == null) { + return false; + } + return contains(otherRange.minimum) + && contains(otherRange.maximum); + } + + /** + *

Checks whether this range is completely after the specified range.

+ * + *

This method may fail if the ranges have two different comparators or element types.

+ * + * @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 otherRange) { + if (otherRange == null) { + return false; + } + return isAfter(otherRange.maximum); + } + + /** + *

Checks whether this range is overlapped by the specified range.

+ * + *

Two ranges overlap if there is at least one element in common.

+ * + *

This method may fail if the ranges have two different comparators or element types.

+ * + * @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 otherRange) { + if (otherRange == null) { + return false; + } + return otherRange.contains(minimum) + || otherRange.contains(maximum) + || contains(otherRange.minimum); + } + + /** + *

Checks whether this range is completely before the specified range.

+ * + *

This method may fail if the ranges have two different comparators or element types.

+ * + * @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 otherRange) { + if (otherRange == null) { + return false; + } + return isBefore(otherRange.minimum); + } + + /** + * 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 intersectionWith(final Range other) { + if (!this.isOverlappedBy(other)) { + throw new IllegalArgumentException(String.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()); + } + + // Basics + //-------------------------------------------------------------------- + + /** + *

Compares this range to another object to test if they are equal.

. + * + *

To be equal, the minimum and maximum values must be equal, which + * ignores any differences in the comparator.

+ * + * @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 range = (Range) obj; + return minimum.equals(range.minimum) && + maximum.equals(range.maximum); + } + } + + /** + *

Gets a suitable hash code for the range.

+ * + * @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; + } + + /** + *

Gets the range as a {@code String}.

+ * + *

The format of the String is '[min..max]'.

+ * + * @return the {@code String} representation of this range + */ + @Override + public String toString() { + if (toString == null) { + toString = "[" + minimum + ".." + maximum + "]"; + } + return toString; + } + + /** + *

Formats the receiver using the given format.

+ * + *

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]}.

+ * + * @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 String.format(format, minimum, maximum, comparator); + } + + //----------------------------------------------------------------------- + @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); + } + } + +} diff --git a/Java/commons-lang-Range_271/metadata.json b/Java/commons-lang-Range_271/metadata.json new file mode 100644 index 000000000..dd79b1855 --- /dev/null +++ b/Java/commons-lang-Range_271/metadata.json @@ -0,0 +1,21 @@ +{ + "language": "java", + "id": "commons-lang-Range_271", + "buggyPath": ".", + "referencePath": null, + "buildCommand": "mvn package -V -B -Denforcer.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true -Drat.skip=true -Dlicense.skip=true -Dfindbugs.skip=true -Dgpg.skip=true -Dskip.npm=true -Dskip.gulp=true -Dskip.bower=true -Drat.numUnapprovedLicenses=100 -DskipTests=true -DskipITs=true -Dtest=None -DfailIfNoTests=false", + "testCommand": "mvn test -V -B -Denforcer.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true -Drat.skip=true -Dlicense.skip=true -Dfindbugs.skip=true -Dgpg.skip=true -Dskip.npm=true -Dskip.gulp=true -Dskip.bower=true -Drat.numUnapprovedLicenses=100", + "categories": [ + "safety", + "npe" + ], + "npe": { + "filepath": "src/main/java/org/apache/commons/lang3/Range.java", + "line": 280, + "npe_method": "isBefore", + "deref_field": "element", + "npe_class": "Range", + "repo": "commons-lang", + "bug_id": "Range_271" + } +} diff --git a/Java/commons-lang-Range_271/npe.json b/Java/commons-lang-Range_271/npe.json new file mode 100644 index 000000000..5ee4c908b --- /dev/null +++ b/Java/commons-lang-Range_271/npe.json @@ -0,0 +1,7 @@ +{ + "filepath": "src/main/java/org/apache/commons/lang3/Range.java", + "line": 280, + "npe_method": "isBefore", + "deref_field": "element", + "npe_class": "Range" +} \ No newline at end of file diff --git a/Java/commons-lang-Range_288/Dockerfile b/Java/commons-lang-Range_288/Dockerfile new file mode 100644 index 000000000..7b7fbe349 --- /dev/null +++ b/Java/commons-lang-Range_288/Dockerfile @@ -0,0 +1,18 @@ +FROM ghcr.io/kupl/starlab-benchmarks/java-base:commons-lang + +ENV TZ=Asia/Seoul + +COPY ./metadata.json . +COPY ./npe.json . +COPY ./buggy.java /tmp/buggy.java +RUN export BUGGY_PATH=$(cat metadata.json | jq -r ".npe.filepath") \ + && export BUGGY_LINE=$(cat metadata.json | jq -r ".npe.line") \ + && export BUGGY_MTHD=$(cat metadata.json | jq -r ".npe.npe_method") \ + && mv /tmp/buggy.java $BUGGY_PATH \ + && echo "[{\"filepath\": \"$BUGGY_PATH\", \"line\": $BUGGY_LINE, \"method_name\": \"$BUGGY_MTHD\"}]" | jq . > traces.json + +RUN git init . && git add -A + +RUN $(cat metadata.json | jq -r ".buildCommand") + +RUN $(cat metadata.json | jq -r ".testCommand"); if [ $? -eq 0 ]; then exit 1; fi diff --git a/Java/commons-lang-Range_288/buggy.java b/Java/commons-lang-Range_288/buggy.java new file mode 100644 index 000000000..58eba2873 --- /dev/null +++ b/Java/commons-lang-Range_288/buggy.java @@ -0,0 +1,497 @@ +/* + * 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; + +/** + *

An immutable range of objects from a minimum to maximum point inclusive.

+ * + *

The objects need to either be implementations of {@code Comparable} + * or you need to supply a {@code Comparator}.

+ * + *

#ThreadSafe# if the objects and comparator are thread-safe

+ * + * @since 3.0 + */ +public final class Range implements Serializable { + + /** + * Serialization version. + * @see java.io.Serializable + */ + private static final long serialVersionUID = 1L; + + /** + * The ordering scheme used in this range. + */ + private final Comparator comparator; + /** + * The minimum value in this range (inclusive). + */ + private final T minimum; + /** + * The maximum value in this range (inclusive). + */ + private final T maximum; + /** + * Cached output hashCode (class is immutable). + */ + private transient int hashCode; + /** + * Cached output toString (class is immutable). + */ + private transient String toString; + + /** + *

Obtains a range using the specified element as both the minimum + * and maximum in this range.

+ * + *

The range uses the natural ordering of the elements to determine where + * values lie in the range.

+ * + * @param 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 > Range is(final T element) { + return between(element, element, null); + } + + /** + *

Obtains a range using the specified element as both the minimum + * and maximum in this range.

+ * + *

The range uses the specified {@code Comparator} to determine where + * values lie in the range.

+ * + * @param 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 Range is(final T element, final Comparator comparator) { + return between(element, element, comparator); + } + + /** + *

Obtains a range with the specified minimum and maximum values (both inclusive).

+ * + *

The range uses the natural ordering of the elements to determine where + * values lie in the range.

+ * + *

The arguments may be passed in the order (min,max) or (max,min). + * The getMinimum and getMaximum methods will return the correct values.

+ * + * @param 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 > Range between(final T fromInclusive, final T toInclusive) { + return between(fromInclusive, toInclusive, null); + } + + /** + *

Obtains a range with the specified minimum and maximum values (both inclusive).

+ * + *

The range uses the specified {@code Comparator} to determine where + * values lie in the range.

+ * + *

The arguments may be passed in the order (min,max) or (max,min). + * The getMinimum and getMaximum methods will return the correct values.

+ * + * @param 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 Range between(final T fromInclusive, final T toInclusive, final Comparator comparator) { + return new Range(fromInclusive, toInclusive, comparator); + } + + /** + * 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 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; + } + } + + // Accessors + //-------------------------------------------------------------------- + + /** + *

Gets the minimum value in this range.

+ * + * @return the minimum value in this range, not null + */ + public T getMinimum() { + return minimum; + } + + /** + *

Gets the maximum value in this range.

+ * + * @return the maximum value in this range, not null + */ + public T getMaximum() { + return maximum; + } + + /** + *

Gets the comparator being used to determine if objects are within the range.

+ * + *

Natural ordering uses an internal comparator implementation, thus this + * method never returns null. See {@link #isNaturalOrdering()}.

+ * + * @return the comparator being used, not null + */ + public Comparator getComparator() { + return comparator; + } + + /** + *

Whether or not the Range is using the natural ordering of the elements.

+ * + *

Natural ordering uses an internal comparator implementation, thus this + * method is the only way to check if a null comparator was specified.

+ * + * @return true if using natural ordering + */ + public boolean isNaturalOrdering() { + return comparator == ComparableComparator.INSTANCE; + } + + // Element tests + //-------------------------------------------------------------------- + + /** + *

Checks whether the specified element occurs within this range.

+ * + * @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; + } + + /** + *

Checks whether this range is after the specified element.

+ * + * @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; + } + + /** + *

Checks whether this range starts with the specified element.

+ * + * @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; + } + + /** + *

Checks whether this range ends with the specified element.

+ * + * @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; + } + + /** + *

Checks whether this range is before the specified element.

+ * + * @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; + } + + /** + *

Checks where the specified element occurs relative to this range.

+ * + *

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.

+ * + * @param element the element to check for, not null + * @return -1, 0 or +1 depending on the element's location relative to the range + */ +/** + *

Checks where the specified element occurs relative to this range.

+ * + *

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.

+ * + * @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) { + { + if (isAfter(/* NPEX_NULL_EXP */ + element)) { + return -1; + } else if (isBefore(element)) { + return 1; + } else { + return 0; + } + } +} + + // Range tests + //-------------------------------------------------------------------- + + /** + *

Checks whether this range contains all the elements of the specified range.

+ * + *

This method may fail if the ranges have two different comparators or element types.

+ * + * @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 otherRange) { + if (otherRange == null) { + return false; + } + return contains(otherRange.minimum) + && contains(otherRange.maximum); + } + + /** + *

Checks whether this range is completely after the specified range.

+ * + *

This method may fail if the ranges have two different comparators or element types.

+ * + * @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 otherRange) { + if (otherRange == null) { + return false; + } + return isAfter(otherRange.maximum); + } + + /** + *

Checks whether this range is overlapped by the specified range.

+ * + *

Two ranges overlap if there is at least one element in common.

+ * + *

This method may fail if the ranges have two different comparators or element types.

+ * + * @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 otherRange) { + if (otherRange == null) { + return false; + } + return otherRange.contains(minimum) + || otherRange.contains(maximum) + || contains(otherRange.minimum); + } + + /** + *

Checks whether this range is completely before the specified range.

+ * + *

This method may fail if the ranges have two different comparators or element types.

+ * + * @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 otherRange) { + if (otherRange == null) { + return false; + } + return isBefore(otherRange.minimum); + } + + /** + * 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 intersectionWith(final Range other) { + if (!this.isOverlappedBy(other)) { + throw new IllegalArgumentException(String.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()); + } + + // Basics + //-------------------------------------------------------------------- + + /** + *

Compares this range to another object to test if they are equal.

. + * + *

To be equal, the minimum and maximum values must be equal, which + * ignores any differences in the comparator.

+ * + * @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 range = (Range) obj; + return minimum.equals(range.minimum) && + maximum.equals(range.maximum); + } + } + + /** + *

Gets a suitable hash code for the range.

+ * + * @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; + } + + /** + *

Gets the range as a {@code String}.

+ * + *

The format of the String is '[min..max]'.

+ * + * @return the {@code String} representation of this range + */ + @Override + public String toString() { + if (toString == null) { + toString = "[" + minimum + ".." + maximum + "]"; + } + return toString; + } + + /** + *

Formats the receiver using the given format.

+ * + *

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]}.

+ * + * @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 String.format(format, minimum, maximum, comparator); + } + + //----------------------------------------------------------------------- + @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); + } + } + +} diff --git a/Java/commons-lang-Range_288/metadata.json b/Java/commons-lang-Range_288/metadata.json new file mode 100644 index 000000000..8969a593d --- /dev/null +++ b/Java/commons-lang-Range_288/metadata.json @@ -0,0 +1,21 @@ +{ + "language": "java", + "id": "commons-lang-Range_288", + "buggyPath": ".", + "referencePath": null, + "buildCommand": "mvn package -V -B -Denforcer.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true -Drat.skip=true -Dlicense.skip=true -Dfindbugs.skip=true -Dgpg.skip=true -Dskip.npm=true -Dskip.gulp=true -Dskip.bower=true -Drat.numUnapprovedLicenses=100 -DskipTests=true -DskipITs=true -Dtest=None -DfailIfNoTests=false", + "testCommand": "mvn test -V -B -Denforcer.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true -Drat.skip=true -Dlicense.skip=true -Dfindbugs.skip=true -Dgpg.skip=true -Dskip.npm=true -Dskip.gulp=true -Dskip.bower=true -Drat.numUnapprovedLicenses=100", + "categories": [ + "safety", + "npe" + ], + "npe": { + "filepath": "src/main/java/org/apache/commons/lang3/Range.java", + "line": 301, + "npe_method": "elementCompareTo", + "deref_field": "element", + "npe_class": "Range", + "repo": "commons-lang", + "bug_id": "Range_288" + } +} diff --git a/Java/commons-lang-Range_288/npe.json b/Java/commons-lang-Range_288/npe.json new file mode 100644 index 000000000..de89fb98e --- /dev/null +++ b/Java/commons-lang-Range_288/npe.json @@ -0,0 +1,7 @@ +{ + "filepath": "src/main/java/org/apache/commons/lang3/Range.java", + "line": 301, + "npe_method": "elementCompareTo", + "deref_field": "element", + "npe_class": "Range" +} \ No newline at end of file diff --git a/Java/commons-lang-Range_314/Dockerfile b/Java/commons-lang-Range_314/Dockerfile new file mode 100644 index 000000000..7b7fbe349 --- /dev/null +++ b/Java/commons-lang-Range_314/Dockerfile @@ -0,0 +1,18 @@ +FROM ghcr.io/kupl/starlab-benchmarks/java-base:commons-lang + +ENV TZ=Asia/Seoul + +COPY ./metadata.json . +COPY ./npe.json . +COPY ./buggy.java /tmp/buggy.java +RUN export BUGGY_PATH=$(cat metadata.json | jq -r ".npe.filepath") \ + && export BUGGY_LINE=$(cat metadata.json | jq -r ".npe.line") \ + && export BUGGY_MTHD=$(cat metadata.json | jq -r ".npe.npe_method") \ + && mv /tmp/buggy.java $BUGGY_PATH \ + && echo "[{\"filepath\": \"$BUGGY_PATH\", \"line\": $BUGGY_LINE, \"method_name\": \"$BUGGY_MTHD\"}]" | jq . > traces.json + +RUN git init . && git add -A + +RUN $(cat metadata.json | jq -r ".buildCommand") + +RUN $(cat metadata.json | jq -r ".testCommand"); if [ $? -eq 0 ]; then exit 1; fi diff --git a/Java/commons-lang-Range_314/buggy.java b/Java/commons-lang-Range_314/buggy.java new file mode 100644 index 000000000..3bf100ac5 --- /dev/null +++ b/Java/commons-lang-Range_314/buggy.java @@ -0,0 +1,499 @@ +/* + * 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; + +/** + *

An immutable range of objects from a minimum to maximum point inclusive.

+ * + *

The objects need to either be implementations of {@code Comparable} + * or you need to supply a {@code Comparator}.

+ * + *

#ThreadSafe# if the objects and comparator are thread-safe

+ * + * @since 3.0 + */ +public final class Range implements Serializable { + + /** + * Serialization version. + * @see java.io.Serializable + */ + private static final long serialVersionUID = 1L; + + /** + * The ordering scheme used in this range. + */ + private final Comparator comparator; + /** + * The minimum value in this range (inclusive). + */ + private final T minimum; + /** + * The maximum value in this range (inclusive). + */ + private final T maximum; + /** + * Cached output hashCode (class is immutable). + */ + private transient int hashCode; + /** + * Cached output toString (class is immutable). + */ + private transient String toString; + + /** + *

Obtains a range using the specified element as both the minimum + * and maximum in this range.

+ * + *

The range uses the natural ordering of the elements to determine where + * values lie in the range.

+ * + * @param 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 > Range is(final T element) { + return between(element, element, null); + } + + /** + *

Obtains a range using the specified element as both the minimum + * and maximum in this range.

+ * + *

The range uses the specified {@code Comparator} to determine where + * values lie in the range.

+ * + * @param 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 Range is(final T element, final Comparator comparator) { + return between(element, element, comparator); + } + + /** + *

Obtains a range with the specified minimum and maximum values (both inclusive).

+ * + *

The range uses the natural ordering of the elements to determine where + * values lie in the range.

+ * + *

The arguments may be passed in the order (min,max) or (max,min). + * The getMinimum and getMaximum methods will return the correct values.

+ * + * @param 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 > Range between(final T fromInclusive, final T toInclusive) { + return between(fromInclusive, toInclusive, null); + } + + /** + *

Obtains a range with the specified minimum and maximum values (both inclusive).

+ * + *

The range uses the specified {@code Comparator} to determine where + * values lie in the range.

+ * + *

The arguments may be passed in the order (min,max) or (max,min). + * The getMinimum and getMaximum methods will return the correct values.

+ * + * @param 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 Range between(final T fromInclusive, final T toInclusive, final Comparator comparator) { + return new Range(fromInclusive, toInclusive, comparator); + } + + /** + * 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 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; + } + } + + // Accessors + //-------------------------------------------------------------------- + + /** + *

Gets the minimum value in this range.

+ * + * @return the minimum value in this range, not null + */ + public T getMinimum() { + return minimum; + } + + /** + *

Gets the maximum value in this range.

+ * + * @return the maximum value in this range, not null + */ + public T getMaximum() { + return maximum; + } + + /** + *

Gets the comparator being used to determine if objects are within the range.

+ * + *

Natural ordering uses an internal comparator implementation, thus this + * method never returns null. See {@link #isNaturalOrdering()}.

+ * + * @return the comparator being used, not null + */ + public Comparator getComparator() { + return comparator; + } + + /** + *

Whether or not the Range is using the natural ordering of the elements.

+ * + *

Natural ordering uses an internal comparator implementation, thus this + * method is the only way to check if a null comparator was specified.

+ * + * @return true if using natural ordering + */ + public boolean isNaturalOrdering() { + return comparator == ComparableComparator.INSTANCE; + } + + // Element tests + //-------------------------------------------------------------------- + + /** + *

Checks whether the specified element occurs within this range.

+ * + * @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; + } + + /** + *

Checks whether this range is after the specified element.

+ * + * @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; + } + + /** + *

Checks whether this range starts with the specified element.

+ * + * @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; + } + + /** + *

Checks whether this range ends with the specified element.

+ * + * @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; + } + + /** + *

Checks whether this range is before the specified element.

+ * + * @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; + } + + /** + *

Checks where the specified element occurs relative to this range.

+ * + *

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.

+ * + * @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) { + if (element == null) { + // Comparable API says throw NPE on null + throw new NullPointerException("Element is null"); + } + if (isAfter(element)) { + return -1; + } else if (isBefore(element)) { + return 1; + } else { + return 0; + } + } + + // Range tests + //-------------------------------------------------------------------- + + /** + *

Checks whether this range contains all the elements of the specified range.

+ * + *

This method may fail if the ranges have two different comparators or element types.

+ * + * @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 + */ +// Range tests +// -------------------------------------------------------------------- +/** + *

Checks whether this range contains all the elements of the specified range.

+ * + *

This method may fail if the ranges have two different comparators or element types.

+ * + * @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 org.apache.commons.lang3.Range otherRange) { + { + return contains(/* NPEX_NULL_EXP */ + otherRange.minimum) && contains(otherRange.maximum); + } +} + + /** + *

Checks whether this range is completely after the specified range.

+ * + *

This method may fail if the ranges have two different comparators or element types.

+ * + * @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 otherRange) { + if (otherRange == null) { + return false; + } + return isAfter(otherRange.maximum); + } + + /** + *

Checks whether this range is overlapped by the specified range.

+ * + *

Two ranges overlap if there is at least one element in common.

+ * + *

This method may fail if the ranges have two different comparators or element types.

+ * + * @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 otherRange) { + if (otherRange == null) { + return false; + } + return otherRange.contains(minimum) + || otherRange.contains(maximum) + || contains(otherRange.minimum); + } + + /** + *

Checks whether this range is completely before the specified range.

+ * + *

This method may fail if the ranges have two different comparators or element types.

+ * + * @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 otherRange) { + if (otherRange == null) { + return false; + } + return isBefore(otherRange.minimum); + } + + /** + * 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 intersectionWith(final Range other) { + if (!this.isOverlappedBy(other)) { + throw new IllegalArgumentException(String.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()); + } + + // Basics + //-------------------------------------------------------------------- + + /** + *

Compares this range to another object to test if they are equal.

. + * + *

To be equal, the minimum and maximum values must be equal, which + * ignores any differences in the comparator.

+ * + * @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 range = (Range) obj; + return minimum.equals(range.minimum) && + maximum.equals(range.maximum); + } + } + + /** + *

Gets a suitable hash code for the range.

+ * + * @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; + } + + /** + *

Gets the range as a {@code String}.

+ * + *

The format of the String is '[min..max]'.

+ * + * @return the {@code String} representation of this range + */ + @Override + public String toString() { + if (toString == null) { + toString = "[" + minimum + ".." + maximum + "]"; + } + return toString; + } + + /** + *

Formats the receiver using the given format.

+ * + *

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]}.

+ * + * @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 String.format(format, minimum, maximum, comparator); + } + + //----------------------------------------------------------------------- + @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); + } + } + +} diff --git a/Java/commons-lang-Range_314/metadata.json b/Java/commons-lang-Range_314/metadata.json new file mode 100644 index 000000000..2b7fb7c18 --- /dev/null +++ b/Java/commons-lang-Range_314/metadata.json @@ -0,0 +1,21 @@ +{ + "language": "java", + "id": "commons-lang-Range_314", + "buggyPath": ".", + "referencePath": null, + "buildCommand": "mvn package -V -B -Denforcer.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true -Drat.skip=true -Dlicense.skip=true -Dfindbugs.skip=true -Dgpg.skip=true -Dskip.npm=true -Dskip.gulp=true -Dskip.bower=true -Drat.numUnapprovedLicenses=100 -DskipTests=true -DskipITs=true -Dtest=None -DfailIfNoTests=false", + "testCommand": "mvn test -V -B -Denforcer.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true -Drat.skip=true -Dlicense.skip=true -Dfindbugs.skip=true -Dgpg.skip=true -Dskip.npm=true -Dskip.gulp=true -Dskip.bower=true -Drat.numUnapprovedLicenses=100", + "categories": [ + "safety", + "npe" + ], + "npe": { + "filepath": "src/main/java/org/apache/commons/lang3/Range.java", + "line": 329, + "npe_method": "containsRange", + "deref_field": "otherRange", + "npe_class": "Range", + "repo": "commons-lang", + "bug_id": "Range_314" + } +} diff --git a/Java/commons-lang-Range_314/npe.json b/Java/commons-lang-Range_314/npe.json new file mode 100644 index 000000000..ecb233c47 --- /dev/null +++ b/Java/commons-lang-Range_314/npe.json @@ -0,0 +1,7 @@ +{ + "filepath": "src/main/java/org/apache/commons/lang3/Range.java", + "line": 329, + "npe_method": "containsRange", + "deref_field": "otherRange", + "npe_class": "Range" +} \ No newline at end of file diff --git a/Java/commons-lang-Range_331/Dockerfile b/Java/commons-lang-Range_331/Dockerfile new file mode 100644 index 000000000..7b7fbe349 --- /dev/null +++ b/Java/commons-lang-Range_331/Dockerfile @@ -0,0 +1,18 @@ +FROM ghcr.io/kupl/starlab-benchmarks/java-base:commons-lang + +ENV TZ=Asia/Seoul + +COPY ./metadata.json . +COPY ./npe.json . +COPY ./buggy.java /tmp/buggy.java +RUN export BUGGY_PATH=$(cat metadata.json | jq -r ".npe.filepath") \ + && export BUGGY_LINE=$(cat metadata.json | jq -r ".npe.line") \ + && export BUGGY_MTHD=$(cat metadata.json | jq -r ".npe.npe_method") \ + && mv /tmp/buggy.java $BUGGY_PATH \ + && echo "[{\"filepath\": \"$BUGGY_PATH\", \"line\": $BUGGY_LINE, \"method_name\": \"$BUGGY_MTHD\"}]" | jq . > traces.json + +RUN git init . && git add -A + +RUN $(cat metadata.json | jq -r ".buildCommand") + +RUN $(cat metadata.json | jq -r ".testCommand"); if [ $? -eq 0 ]; then exit 1; fi diff --git a/Java/commons-lang-Range_331/buggy.java b/Java/commons-lang-Range_331/buggy.java new file mode 100644 index 000000000..41ff344b4 --- /dev/null +++ b/Java/commons-lang-Range_331/buggy.java @@ -0,0 +1,498 @@ +/* + * 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; + +/** + *

An immutable range of objects from a minimum to maximum point inclusive.

+ * + *

The objects need to either be implementations of {@code Comparable} + * or you need to supply a {@code Comparator}.

+ * + *

#ThreadSafe# if the objects and comparator are thread-safe

+ * + * @since 3.0 + */ +public final class Range implements Serializable { + + /** + * Serialization version. + * @see java.io.Serializable + */ + private static final long serialVersionUID = 1L; + + /** + * The ordering scheme used in this range. + */ + private final Comparator comparator; + /** + * The minimum value in this range (inclusive). + */ + private final T minimum; + /** + * The maximum value in this range (inclusive). + */ + private final T maximum; + /** + * Cached output hashCode (class is immutable). + */ + private transient int hashCode; + /** + * Cached output toString (class is immutable). + */ + private transient String toString; + + /** + *

Obtains a range using the specified element as both the minimum + * and maximum in this range.

+ * + *

The range uses the natural ordering of the elements to determine where + * values lie in the range.

+ * + * @param 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 > Range is(final T element) { + return between(element, element, null); + } + + /** + *

Obtains a range using the specified element as both the minimum + * and maximum in this range.

+ * + *

The range uses the specified {@code Comparator} to determine where + * values lie in the range.

+ * + * @param 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 Range is(final T element, final Comparator comparator) { + return between(element, element, comparator); + } + + /** + *

Obtains a range with the specified minimum and maximum values (both inclusive).

+ * + *

The range uses the natural ordering of the elements to determine where + * values lie in the range.

+ * + *

The arguments may be passed in the order (min,max) or (max,min). + * The getMinimum and getMaximum methods will return the correct values.

+ * + * @param 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 > Range between(final T fromInclusive, final T toInclusive) { + return between(fromInclusive, toInclusive, null); + } + + /** + *

Obtains a range with the specified minimum and maximum values (both inclusive).

+ * + *

The range uses the specified {@code Comparator} to determine where + * values lie in the range.

+ * + *

The arguments may be passed in the order (min,max) or (max,min). + * The getMinimum and getMaximum methods will return the correct values.

+ * + * @param 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 Range between(final T fromInclusive, final T toInclusive, final Comparator comparator) { + return new Range(fromInclusive, toInclusive, comparator); + } + + /** + * 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 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; + } + } + + // Accessors + //-------------------------------------------------------------------- + + /** + *

Gets the minimum value in this range.

+ * + * @return the minimum value in this range, not null + */ + public T getMinimum() { + return minimum; + } + + /** + *

Gets the maximum value in this range.

+ * + * @return the maximum value in this range, not null + */ + public T getMaximum() { + return maximum; + } + + /** + *

Gets the comparator being used to determine if objects are within the range.

+ * + *

Natural ordering uses an internal comparator implementation, thus this + * method never returns null. See {@link #isNaturalOrdering()}.

+ * + * @return the comparator being used, not null + */ + public Comparator getComparator() { + return comparator; + } + + /** + *

Whether or not the Range is using the natural ordering of the elements.

+ * + *

Natural ordering uses an internal comparator implementation, thus this + * method is the only way to check if a null comparator was specified.

+ * + * @return true if using natural ordering + */ + public boolean isNaturalOrdering() { + return comparator == ComparableComparator.INSTANCE; + } + + // Element tests + //-------------------------------------------------------------------- + + /** + *

Checks whether the specified element occurs within this range.

+ * + * @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; + } + + /** + *

Checks whether this range is after the specified element.

+ * + * @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; + } + + /** + *

Checks whether this range starts with the specified element.

+ * + * @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; + } + + /** + *

Checks whether this range ends with the specified element.

+ * + * @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; + } + + /** + *

Checks whether this range is before the specified element.

+ * + * @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; + } + + /** + *

Checks where the specified element occurs relative to this range.

+ * + *

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.

+ * + * @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) { + if (element == null) { + // Comparable API says throw NPE on null + throw new NullPointerException("Element is null"); + } + if (isAfter(element)) { + return -1; + } else if (isBefore(element)) { + return 1; + } else { + return 0; + } + } + + // Range tests + //-------------------------------------------------------------------- + + /** + *

Checks whether this range contains all the elements of the specified range.

+ * + *

This method may fail if the ranges have two different comparators or element types.

+ * + * @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 otherRange) { + if (otherRange == null) { + return false; + } + return contains(otherRange.minimum) + && contains(otherRange.maximum); + } + + /** + *

Checks whether this range is completely after the specified range.

+ * + *

This method may fail if the ranges have two different comparators or element types.

+ * + * @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 + */ +/** + *

Checks whether this range is completely after the specified range.

+ * + *

This method may fail if the ranges have two different comparators or element types.

+ * + * @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 org.apache.commons.lang3.Range otherRange) { + { + return isAfter(/* NPEX_NULL_EXP */ + otherRange.maximum); + } +} + + /** + *

Checks whether this range is overlapped by the specified range.

+ * + *

Two ranges overlap if there is at least one element in common.

+ * + *

This method may fail if the ranges have two different comparators or element types.

+ * + * @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 otherRange) { + if (otherRange == null) { + return false; + } + return otherRange.contains(minimum) + || otherRange.contains(maximum) + || contains(otherRange.minimum); + } + + /** + *

Checks whether this range is completely before the specified range.

+ * + *

This method may fail if the ranges have two different comparators or element types.

+ * + * @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 otherRange) { + if (otherRange == null) { + return false; + } + return isBefore(otherRange.minimum); + } + + /** + * 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 intersectionWith(final Range other) { + if (!this.isOverlappedBy(other)) { + throw new IllegalArgumentException(String.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()); + } + + // Basics + //-------------------------------------------------------------------- + + /** + *

Compares this range to another object to test if they are equal.

. + * + *

To be equal, the minimum and maximum values must be equal, which + * ignores any differences in the comparator.

+ * + * @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 range = (Range) obj; + return minimum.equals(range.minimum) && + maximum.equals(range.maximum); + } + } + + /** + *

Gets a suitable hash code for the range.

+ * + * @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; + } + + /** + *

Gets the range as a {@code String}.

+ * + *

The format of the String is '[min..max]'.

+ * + * @return the {@code String} representation of this range + */ + @Override + public String toString() { + if (toString == null) { + toString = "[" + minimum + ".." + maximum + "]"; + } + return toString; + } + + /** + *

Formats the receiver using the given format.

+ * + *

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]}.

+ * + * @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 String.format(format, minimum, maximum, comparator); + } + + //----------------------------------------------------------------------- + @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); + } + } + +} diff --git a/Java/commons-lang-Range_331/metadata.json b/Java/commons-lang-Range_331/metadata.json new file mode 100644 index 000000000..e69bcf47b --- /dev/null +++ b/Java/commons-lang-Range_331/metadata.json @@ -0,0 +1,21 @@ +{ + "language": "java", + "id": "commons-lang-Range_331", + "buggyPath": ".", + "referencePath": null, + "buildCommand": "mvn package -V -B -Denforcer.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true -Drat.skip=true -Dlicense.skip=true -Dfindbugs.skip=true -Dgpg.skip=true -Dskip.npm=true -Dskip.gulp=true -Dskip.bower=true -Drat.numUnapprovedLicenses=100 -DskipTests=true -DskipITs=true -Dtest=None -DfailIfNoTests=false", + "testCommand": "mvn test -V -B -Denforcer.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true -Drat.skip=true -Dlicense.skip=true -Dfindbugs.skip=true -Dgpg.skip=true -Dskip.npm=true -Dskip.gulp=true -Dskip.bower=true -Drat.numUnapprovedLicenses=100", + "categories": [ + "safety", + "npe" + ], + "npe": { + "filepath": "src/main/java/org/apache/commons/lang3/Range.java", + "line": 344, + "npe_method": "isAfterRange", + "deref_field": "otherRange", + "npe_class": "Range", + "repo": "commons-lang", + "bug_id": "Range_331" + } +} diff --git a/Java/commons-lang-Range_331/npe.json b/Java/commons-lang-Range_331/npe.json new file mode 100644 index 000000000..ea12163a3 --- /dev/null +++ b/Java/commons-lang-Range_331/npe.json @@ -0,0 +1,7 @@ +{ + "filepath": "src/main/java/org/apache/commons/lang3/Range.java", + "line": 344, + "npe_method": "isAfterRange", + "deref_field": "otherRange", + "npe_class": "Range" +} \ No newline at end of file diff --git a/Java/commons-lang-Range_350/Dockerfile b/Java/commons-lang-Range_350/Dockerfile new file mode 100644 index 000000000..7b7fbe349 --- /dev/null +++ b/Java/commons-lang-Range_350/Dockerfile @@ -0,0 +1,18 @@ +FROM ghcr.io/kupl/starlab-benchmarks/java-base:commons-lang + +ENV TZ=Asia/Seoul + +COPY ./metadata.json . +COPY ./npe.json . +COPY ./buggy.java /tmp/buggy.java +RUN export BUGGY_PATH=$(cat metadata.json | jq -r ".npe.filepath") \ + && export BUGGY_LINE=$(cat metadata.json | jq -r ".npe.line") \ + && export BUGGY_MTHD=$(cat metadata.json | jq -r ".npe.npe_method") \ + && mv /tmp/buggy.java $BUGGY_PATH \ + && echo "[{\"filepath\": \"$BUGGY_PATH\", \"line\": $BUGGY_LINE, \"method_name\": \"$BUGGY_MTHD\"}]" | jq . > traces.json + +RUN git init . && git add -A + +RUN $(cat metadata.json | jq -r ".buildCommand") + +RUN $(cat metadata.json | jq -r ".testCommand"); if [ $? -eq 0 ]; then exit 1; fi diff --git a/Java/commons-lang-Range_350/buggy.java b/Java/commons-lang-Range_350/buggy.java new file mode 100644 index 000000000..631f0f49f --- /dev/null +++ b/Java/commons-lang-Range_350/buggy.java @@ -0,0 +1,499 @@ +/* + * 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; + +/** + *

An immutable range of objects from a minimum to maximum point inclusive.

+ * + *

The objects need to either be implementations of {@code Comparable} + * or you need to supply a {@code Comparator}.

+ * + *

#ThreadSafe# if the objects and comparator are thread-safe

+ * + * @since 3.0 + */ +public final class Range implements Serializable { + + /** + * Serialization version. + * @see java.io.Serializable + */ + private static final long serialVersionUID = 1L; + + /** + * The ordering scheme used in this range. + */ + private final Comparator comparator; + /** + * The minimum value in this range (inclusive). + */ + private final T minimum; + /** + * The maximum value in this range (inclusive). + */ + private final T maximum; + /** + * Cached output hashCode (class is immutable). + */ + private transient int hashCode; + /** + * Cached output toString (class is immutable). + */ + private transient String toString; + + /** + *

Obtains a range using the specified element as both the minimum + * and maximum in this range.

+ * + *

The range uses the natural ordering of the elements to determine where + * values lie in the range.

+ * + * @param 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 > Range is(final T element) { + return between(element, element, null); + } + + /** + *

Obtains a range using the specified element as both the minimum + * and maximum in this range.

+ * + *

The range uses the specified {@code Comparator} to determine where + * values lie in the range.

+ * + * @param 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 Range is(final T element, final Comparator comparator) { + return between(element, element, comparator); + } + + /** + *

Obtains a range with the specified minimum and maximum values (both inclusive).

+ * + *

The range uses the natural ordering of the elements to determine where + * values lie in the range.

+ * + *

The arguments may be passed in the order (min,max) or (max,min). + * The getMinimum and getMaximum methods will return the correct values.

+ * + * @param 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 > Range between(final T fromInclusive, final T toInclusive) { + return between(fromInclusive, toInclusive, null); + } + + /** + *

Obtains a range with the specified minimum and maximum values (both inclusive).

+ * + *

The range uses the specified {@code Comparator} to determine where + * values lie in the range.

+ * + *

The arguments may be passed in the order (min,max) or (max,min). + * The getMinimum and getMaximum methods will return the correct values.

+ * + * @param 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 Range between(final T fromInclusive, final T toInclusive, final Comparator comparator) { + return new Range(fromInclusive, toInclusive, comparator); + } + + /** + * 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 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; + } + } + + // Accessors + //-------------------------------------------------------------------- + + /** + *

Gets the minimum value in this range.

+ * + * @return the minimum value in this range, not null + */ + public T getMinimum() { + return minimum; + } + + /** + *

Gets the maximum value in this range.

+ * + * @return the maximum value in this range, not null + */ + public T getMaximum() { + return maximum; + } + + /** + *

Gets the comparator being used to determine if objects are within the range.

+ * + *

Natural ordering uses an internal comparator implementation, thus this + * method never returns null. See {@link #isNaturalOrdering()}.

+ * + * @return the comparator being used, not null + */ + public Comparator getComparator() { + return comparator; + } + + /** + *

Whether or not the Range is using the natural ordering of the elements.

+ * + *

Natural ordering uses an internal comparator implementation, thus this + * method is the only way to check if a null comparator was specified.

+ * + * @return true if using natural ordering + */ + public boolean isNaturalOrdering() { + return comparator == ComparableComparator.INSTANCE; + } + + // Element tests + //-------------------------------------------------------------------- + + /** + *

Checks whether the specified element occurs within this range.

+ * + * @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; + } + + /** + *

Checks whether this range is after the specified element.

+ * + * @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; + } + + /** + *

Checks whether this range starts with the specified element.

+ * + * @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; + } + + /** + *

Checks whether this range ends with the specified element.

+ * + * @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; + } + + /** + *

Checks whether this range is before the specified element.

+ * + * @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; + } + + /** + *

Checks where the specified element occurs relative to this range.

+ * + *

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.

+ * + * @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) { + if (element == null) { + // Comparable API says throw NPE on null + throw new NullPointerException("Element is null"); + } + if (isAfter(element)) { + return -1; + } else if (isBefore(element)) { + return 1; + } else { + return 0; + } + } + + // Range tests + //-------------------------------------------------------------------- + + /** + *

Checks whether this range contains all the elements of the specified range.

+ * + *

This method may fail if the ranges have two different comparators or element types.

+ * + * @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 otherRange) { + if (otherRange == null) { + return false; + } + return contains(otherRange.minimum) + && contains(otherRange.maximum); + } + + /** + *

Checks whether this range is completely after the specified range.

+ * + *

This method may fail if the ranges have two different comparators or element types.

+ * + * @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 otherRange) { + if (otherRange == null) { + return false; + } + return isAfter(otherRange.maximum); + } + + /** + *

Checks whether this range is overlapped by the specified range.

+ * + *

Two ranges overlap if there is at least one element in common.

+ * + *

This method may fail if the ranges have two different comparators or element types.

+ * + * @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 + */ +/** + *

Checks whether this range is overlapped by the specified range.

+ * + *

Two ranges overlap if there is at least one element in common.

+ * + *

This method may fail if the ranges have two different comparators or element types.

+ * + * @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 org.apache.commons.lang3.Range otherRange) { + { + return (/* NPEX_NULL_EXP */ + otherRange.contains(minimum) || otherRange.contains(maximum)) || contains(otherRange.minimum); + } +} + + /** + *

Checks whether this range is completely before the specified range.

+ * + *

This method may fail if the ranges have two different comparators or element types.

+ * + * @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 otherRange) { + if (otherRange == null) { + return false; + } + return isBefore(otherRange.minimum); + } + + /** + * 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 intersectionWith(final Range other) { + if (!this.isOverlappedBy(other)) { + throw new IllegalArgumentException(String.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()); + } + + // Basics + //-------------------------------------------------------------------- + + /** + *

Compares this range to another object to test if they are equal.

. + * + *

To be equal, the minimum and maximum values must be equal, which + * ignores any differences in the comparator.

+ * + * @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 range = (Range) obj; + return minimum.equals(range.minimum) && + maximum.equals(range.maximum); + } + } + + /** + *

Gets a suitable hash code for the range.

+ * + * @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; + } + + /** + *

Gets the range as a {@code String}.

+ * + *

The format of the String is '[min..max]'.

+ * + * @return the {@code String} representation of this range + */ + @Override + public String toString() { + if (toString == null) { + toString = "[" + minimum + ".." + maximum + "]"; + } + return toString; + } + + /** + *

Formats the receiver using the given format.

+ * + *

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]}.

+ * + * @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 String.format(format, minimum, maximum, comparator); + } + + //----------------------------------------------------------------------- + @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); + } + } + +} diff --git a/Java/commons-lang-Range_350/metadata.json b/Java/commons-lang-Range_350/metadata.json new file mode 100644 index 000000000..58192c64b --- /dev/null +++ b/Java/commons-lang-Range_350/metadata.json @@ -0,0 +1,21 @@ +{ + "language": "java", + "id": "commons-lang-Range_350", + "buggyPath": ".", + "referencePath": null, + "buildCommand": "mvn package -V -B -Denforcer.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true -Drat.skip=true -Dlicense.skip=true -Dfindbugs.skip=true -Dgpg.skip=true -Dskip.npm=true -Dskip.gulp=true -Dskip.bower=true -Drat.numUnapprovedLicenses=100 -DskipTests=true -DskipITs=true -Dtest=None -DfailIfNoTests=false", + "testCommand": "mvn test -V -B -Denforcer.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true -Drat.skip=true -Dlicense.skip=true -Dfindbugs.skip=true -Dgpg.skip=true -Dskip.npm=true -Dskip.gulp=true -Dskip.bower=true -Drat.numUnapprovedLicenses=100", + "categories": [ + "safety", + "npe" + ], + "npe": { + "filepath": "src/main/java/org/apache/commons/lang3/Range.java", + "line": 366, + "npe_method": "isOverlappedBy", + "deref_field": "otherRange", + "npe_class": "Range", + "repo": "commons-lang", + "bug_id": "Range_350" + } +} diff --git a/Java/commons-lang-Range_350/npe.json b/Java/commons-lang-Range_350/npe.json new file mode 100644 index 000000000..c50e6ba09 --- /dev/null +++ b/Java/commons-lang-Range_350/npe.json @@ -0,0 +1,7 @@ +{ + "filepath": "src/main/java/org/apache/commons/lang3/Range.java", + "line": 366, + "npe_method": "isOverlappedBy", + "deref_field": "otherRange", + "npe_class": "Range" +} \ No newline at end of file diff --git a/Java/commons-lang-Range_368/Dockerfile b/Java/commons-lang-Range_368/Dockerfile new file mode 100644 index 000000000..7b7fbe349 --- /dev/null +++ b/Java/commons-lang-Range_368/Dockerfile @@ -0,0 +1,18 @@ +FROM ghcr.io/kupl/starlab-benchmarks/java-base:commons-lang + +ENV TZ=Asia/Seoul + +COPY ./metadata.json . +COPY ./npe.json . +COPY ./buggy.java /tmp/buggy.java +RUN export BUGGY_PATH=$(cat metadata.json | jq -r ".npe.filepath") \ + && export BUGGY_LINE=$(cat metadata.json | jq -r ".npe.line") \ + && export BUGGY_MTHD=$(cat metadata.json | jq -r ".npe.npe_method") \ + && mv /tmp/buggy.java $BUGGY_PATH \ + && echo "[{\"filepath\": \"$BUGGY_PATH\", \"line\": $BUGGY_LINE, \"method_name\": \"$BUGGY_MTHD\"}]" | jq . > traces.json + +RUN git init . && git add -A + +RUN $(cat metadata.json | jq -r ".buildCommand") + +RUN $(cat metadata.json | jq -r ".testCommand"); if [ $? -eq 0 ]; then exit 1; fi diff --git a/Java/commons-lang-Range_368/buggy.java b/Java/commons-lang-Range_368/buggy.java new file mode 100644 index 000000000..d9385fdec --- /dev/null +++ b/Java/commons-lang-Range_368/buggy.java @@ -0,0 +1,498 @@ +/* + * 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; + +/** + *

An immutable range of objects from a minimum to maximum point inclusive.

+ * + *

The objects need to either be implementations of {@code Comparable} + * or you need to supply a {@code Comparator}.

+ * + *

#ThreadSafe# if the objects and comparator are thread-safe

+ * + * @since 3.0 + */ +public final class Range implements Serializable { + + /** + * Serialization version. + * @see java.io.Serializable + */ + private static final long serialVersionUID = 1L; + + /** + * The ordering scheme used in this range. + */ + private final Comparator comparator; + /** + * The minimum value in this range (inclusive). + */ + private final T minimum; + /** + * The maximum value in this range (inclusive). + */ + private final T maximum; + /** + * Cached output hashCode (class is immutable). + */ + private transient int hashCode; + /** + * Cached output toString (class is immutable). + */ + private transient String toString; + + /** + *

Obtains a range using the specified element as both the minimum + * and maximum in this range.

+ * + *

The range uses the natural ordering of the elements to determine where + * values lie in the range.

+ * + * @param 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 > Range is(final T element) { + return between(element, element, null); + } + + /** + *

Obtains a range using the specified element as both the minimum + * and maximum in this range.

+ * + *

The range uses the specified {@code Comparator} to determine where + * values lie in the range.

+ * + * @param 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 Range is(final T element, final Comparator comparator) { + return between(element, element, comparator); + } + + /** + *

Obtains a range with the specified minimum and maximum values (both inclusive).

+ * + *

The range uses the natural ordering of the elements to determine where + * values lie in the range.

+ * + *

The arguments may be passed in the order (min,max) or (max,min). + * The getMinimum and getMaximum methods will return the correct values.

+ * + * @param 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 > Range between(final T fromInclusive, final T toInclusive) { + return between(fromInclusive, toInclusive, null); + } + + /** + *

Obtains a range with the specified minimum and maximum values (both inclusive).

+ * + *

The range uses the specified {@code Comparator} to determine where + * values lie in the range.

+ * + *

The arguments may be passed in the order (min,max) or (max,min). + * The getMinimum and getMaximum methods will return the correct values.

+ * + * @param 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 Range between(final T fromInclusive, final T toInclusive, final Comparator comparator) { + return new Range(fromInclusive, toInclusive, comparator); + } + + /** + * 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 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; + } + } + + // Accessors + //-------------------------------------------------------------------- + + /** + *

Gets the minimum value in this range.

+ * + * @return the minimum value in this range, not null + */ + public T getMinimum() { + return minimum; + } + + /** + *

Gets the maximum value in this range.

+ * + * @return the maximum value in this range, not null + */ + public T getMaximum() { + return maximum; + } + + /** + *

Gets the comparator being used to determine if objects are within the range.

+ * + *

Natural ordering uses an internal comparator implementation, thus this + * method never returns null. See {@link #isNaturalOrdering()}.

+ * + * @return the comparator being used, not null + */ + public Comparator getComparator() { + return comparator; + } + + /** + *

Whether or not the Range is using the natural ordering of the elements.

+ * + *

Natural ordering uses an internal comparator implementation, thus this + * method is the only way to check if a null comparator was specified.

+ * + * @return true if using natural ordering + */ + public boolean isNaturalOrdering() { + return comparator == ComparableComparator.INSTANCE; + } + + // Element tests + //-------------------------------------------------------------------- + + /** + *

Checks whether the specified element occurs within this range.

+ * + * @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; + } + + /** + *

Checks whether this range is after the specified element.

+ * + * @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; + } + + /** + *

Checks whether this range starts with the specified element.

+ * + * @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; + } + + /** + *

Checks whether this range ends with the specified element.

+ * + * @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; + } + + /** + *

Checks whether this range is before the specified element.

+ * + * @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; + } + + /** + *

Checks where the specified element occurs relative to this range.

+ * + *

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.

+ * + * @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) { + if (element == null) { + // Comparable API says throw NPE on null + throw new NullPointerException("Element is null"); + } + if (isAfter(element)) { + return -1; + } else if (isBefore(element)) { + return 1; + } else { + return 0; + } + } + + // Range tests + //-------------------------------------------------------------------- + + /** + *

Checks whether this range contains all the elements of the specified range.

+ * + *

This method may fail if the ranges have two different comparators or element types.

+ * + * @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 otherRange) { + if (otherRange == null) { + return false; + } + return contains(otherRange.minimum) + && contains(otherRange.maximum); + } + + /** + *

Checks whether this range is completely after the specified range.

+ * + *

This method may fail if the ranges have two different comparators or element types.

+ * + * @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 otherRange) { + if (otherRange == null) { + return false; + } + return isAfter(otherRange.maximum); + } + + /** + *

Checks whether this range is overlapped by the specified range.

+ * + *

Two ranges overlap if there is at least one element in common.

+ * + *

This method may fail if the ranges have two different comparators or element types.

+ * + * @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 otherRange) { + if (otherRange == null) { + return false; + } + return otherRange.contains(minimum) + || otherRange.contains(maximum) + || contains(otherRange.minimum); + } + + /** + *

Checks whether this range is completely before the specified range.

+ * + *

This method may fail if the ranges have two different comparators or element types.

+ * + * @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 + */ +/** + *

Checks whether this range is completely before the specified range.

+ * + *

This method may fail if the ranges have two different comparators or element types.

+ * + * @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 org.apache.commons.lang3.Range otherRange) { + { + return isBefore(/* NPEX_NULL_EXP */ + otherRange.minimum); + } +} + + /** + * 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 intersectionWith(final Range other) { + if (!this.isOverlappedBy(other)) { + throw new IllegalArgumentException(String.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()); + } + + // Basics + //-------------------------------------------------------------------- + + /** + *

Compares this range to another object to test if they are equal.

. + * + *

To be equal, the minimum and maximum values must be equal, which + * ignores any differences in the comparator.

+ * + * @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 range = (Range) obj; + return minimum.equals(range.minimum) && + maximum.equals(range.maximum); + } + } + + /** + *

Gets a suitable hash code for the range.

+ * + * @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; + } + + /** + *

Gets the range as a {@code String}.

+ * + *

The format of the String is '[min..max]'.

+ * + * @return the {@code String} representation of this range + */ + @Override + public String toString() { + if (toString == null) { + toString = "[" + minimum + ".." + maximum + "]"; + } + return toString; + } + + /** + *

Formats the receiver using the given format.

+ * + *

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]}.

+ * + * @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 String.format(format, minimum, maximum, comparator); + } + + //----------------------------------------------------------------------- + @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); + } + } + +} diff --git a/Java/commons-lang-Range_368/metadata.json b/Java/commons-lang-Range_368/metadata.json new file mode 100644 index 000000000..a1b269c15 --- /dev/null +++ b/Java/commons-lang-Range_368/metadata.json @@ -0,0 +1,21 @@ +{ + "language": "java", + "id": "commons-lang-Range_368", + "buggyPath": ".", + "referencePath": null, + "buildCommand": "mvn package -V -B -Denforcer.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true -Drat.skip=true -Dlicense.skip=true -Dfindbugs.skip=true -Dgpg.skip=true -Dskip.npm=true -Dskip.gulp=true -Dskip.bower=true -Drat.numUnapprovedLicenses=100 -DskipTests=true -DskipITs=true -Dtest=None -DfailIfNoTests=false", + "testCommand": "mvn test -V -B -Denforcer.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true -Drat.skip=true -Dlicense.skip=true -Dfindbugs.skip=true -Dgpg.skip=true -Dskip.npm=true -Dskip.gulp=true -Dskip.bower=true -Drat.numUnapprovedLicenses=100", + "categories": [ + "safety", + "npe" + ], + "npe": { + "filepath": "src/main/java/org/apache/commons/lang3/Range.java", + "line": 381, + "npe_method": "isBeforeRange", + "deref_field": "otherRange", + "npe_class": "Range", + "repo": "commons-lang", + "bug_id": "Range_368" + } +} diff --git a/Java/commons-lang-Range_368/npe.json b/Java/commons-lang-Range_368/npe.json new file mode 100644 index 000000000..d9db12e5d --- /dev/null +++ b/Java/commons-lang-Range_368/npe.json @@ -0,0 +1,7 @@ +{ + "filepath": "src/main/java/org/apache/commons/lang3/Range.java", + "line": 381, + "npe_method": "isBeforeRange", + "deref_field": "otherRange", + "npe_class": "Range" +} \ No newline at end of file diff --git a/Java/commons-lang-ReflectionToStringBuilder_327/Dockerfile b/Java/commons-lang-ReflectionToStringBuilder_327/Dockerfile new file mode 100644 index 000000000..7b7fbe349 --- /dev/null +++ b/Java/commons-lang-ReflectionToStringBuilder_327/Dockerfile @@ -0,0 +1,18 @@ +FROM ghcr.io/kupl/starlab-benchmarks/java-base:commons-lang + +ENV TZ=Asia/Seoul + +COPY ./metadata.json . +COPY ./npe.json . +COPY ./buggy.java /tmp/buggy.java +RUN export BUGGY_PATH=$(cat metadata.json | jq -r ".npe.filepath") \ + && export BUGGY_LINE=$(cat metadata.json | jq -r ".npe.line") \ + && export BUGGY_MTHD=$(cat metadata.json | jq -r ".npe.npe_method") \ + && mv /tmp/buggy.java $BUGGY_PATH \ + && echo "[{\"filepath\": \"$BUGGY_PATH\", \"line\": $BUGGY_LINE, \"method_name\": \"$BUGGY_MTHD\"}]" | jq . > traces.json + +RUN git init . && git add -A + +RUN $(cat metadata.json | jq -r ".buildCommand") + +RUN $(cat metadata.json | jq -r ".testCommand"); if [ $? -eq 0 ]; then exit 1; fi diff --git a/Java/commons-lang-ReflectionToStringBuilder_327/buggy.java b/Java/commons-lang-ReflectionToStringBuilder_327/buggy.java new file mode 100644 index 000000000..9ad3d1de3 --- /dev/null +++ b/Java/commons-lang-ReflectionToStringBuilder_327/buggy.java @@ -0,0 +1,728 @@ +/* + * 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.reflect.AccessibleObject; +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; + +import org.apache.commons.lang3.ArrayUtils; +import org.apache.commons.lang3.ClassUtils; + +/** + *

+ * Assists in implementing {@link Object#toString()} methods using reflection. + *

+ *

+ * This class uses reflection to determine the fields to append. Because these fields are usually private, the class + * uses {@link java.lang.reflect.AccessibleObject#setAccessible(java.lang.reflect.AccessibleObject[], boolean)} to + * change the visibility of the fields. This will fail under a security manager, unless the appropriate permissions are + * set up correctly. + *

+ *

+ * Using reflection to access (private) fields circumvents any synchronization protection guarding access to these + * fields. If a toString method cannot safely read a field, you should exclude it from the toString method, or use + * synchronization consistent with the class' lock management around the invocation of the method. Take special care to + * exclude non-thread-safe collection classes, because these classes may throw ConcurrentModificationException if + * modified while the toString method is executing. + *

+ *

+ * A typical invocation for this method would look like: + *

+ *
+ * public String toString() {
+ *     return ReflectionToStringBuilder.toString(this);
+ * }
+ * 
+ *

+ * You can also use the builder to debug 3rd party objects: + *

+ *
+ * System.out.println("An object: " + ReflectionToStringBuilder.toString(anObject));
+ * 
+ *

+ * A subclass can control field output by overriding the methods: + *

+ *
    + *
  • {@link #accept(java.lang.reflect.Field)}
  • + *
  • {@link #getValue(java.lang.reflect.Field)}
  • + *
+ *

+ * For example, this method does not include the password field in the returned String: + *

+ *
+ * public String toString() {
+ *     return (new ReflectionToStringBuilder(this) {
+ *         protected boolean accept(Field f) {
+ *             return super.accept(f) && !f.getName().equals("password");
+ *         }
+ *     }).toString();
+ * }
+ * 
+ *

+ * Alternatively the {@link ToStringExclude} annotation can be used to exclude fields from being incorporated in the + * result. + *

+ *

+ * The exact format of the toString is determined by the {@link ToStringStyle} passed into the constructor. + *

+ * + *

+ * Note: the default {@link ToStringStyle} will only do a "shallow" formatting, i.e. composed objects are not + * further traversed. To get "deep" formatting, use an instance of {@link RecursiveToStringStyle}. + *

+ * + * @since 2.0 + */ +public class ReflectionToStringBuilder extends ToStringBuilder { + + /** + *

+ * Builds a toString value using the default ToStringStyle through reflection. + *

+ * + *

+ * It uses AccessibleObject.setAccessible to gain access to private fields. This means that it will + * throw a security exception if run under a security manager, if the permissions are not set up correctly. It is + * also not as efficient as testing explicitly. + *

+ * + *

+ * Transient members will be not be included, as they are likely derived. Static fields will not be included. + * Superclass fields will be appended. + *

+ * + * @param object + * the Object to be output + * @return the String result + * @throws IllegalArgumentException + * if the Object is null + * + * @see ToStringExclude + */ + public static String toString(final Object object) { + return toString(object, null, false, false, null); + } + + /** + *

+ * Builds a toString value through reflection. + *

+ * + *

+ * It uses AccessibleObject.setAccessible to gain access to private fields. This means that it will + * throw a security exception if run under a security manager, if the permissions are not set up correctly. It is + * also not as efficient as testing explicitly. + *

+ * + *

+ * Transient members will be not be included, as they are likely derived. Static fields will not be included. + * Superclass fields will be appended. + *

+ * + *

+ * If the style is null, the default ToStringStyle is used. + *

+ * + * @param object + * the Object to be output + * @param style + * the style of the toString to create, may be null + * @return the String result + * @throws IllegalArgumentException + * if the Object or ToStringStyle is null + * + * @see ToStringExclude + */ + public static String toString(final Object object, final ToStringStyle style) { + return toString(object, style, false, false, null); + } + + /** + *

+ * Builds a toString value through reflection. + *

+ * + *

+ * It uses AccessibleObject.setAccessible to gain access to private fields. This means that it will + * throw a security exception if run under a security manager, if the permissions are not set up correctly. It is + * also not as efficient as testing explicitly. + *

+ * + *

+ * If the outputTransients is true, transient members will be output, otherwise they + * are ignored, as they are likely derived fields, and not part of the value of the Object. + *

+ * + *

+ * Static fields will not be included. Superclass fields will be appended. + *

+ * + *

+ * If the style is null, the default ToStringStyle is used. + *

+ * + * @param object + * the Object to be output + * @param style + * the style of the toString to create, may be null + * @param outputTransients + * whether to include transient fields + * @return the String result + * @throws IllegalArgumentException + * if the Object is null + * + * @see ToStringExclude + */ + public static String toString(final Object object, final ToStringStyle style, final boolean outputTransients) { + return toString(object, style, outputTransients, false, null); + } + + /** + *

+ * Builds a toString value through reflection. + *

+ * + *

+ * It uses AccessibleObject.setAccessible to gain access to private fields. This means that it will + * throw a security exception if run under a security manager, if the permissions are not set up correctly. It is + * also not as efficient as testing explicitly. + *

+ * + *

+ * If the outputTransients is true, transient fields will be output, otherwise they + * are ignored, as they are likely derived fields, and not part of the value of the Object. + *

+ * + *

+ * If the outputStatics is true, static fields will be output, otherwise they are + * ignored. + *

+ * + *

+ * Static fields will not be included. Superclass fields will be appended. + *

+ * + *

+ * If the style is null, the default ToStringStyle is used. + *

+ * + * @param object + * the Object to be output + * @param style + * the style of the toString to create, may be null + * @param outputTransients + * whether to include transient fields + * @param outputStatics + * whether to include static fields + * @return the String result + * @throws IllegalArgumentException + * if the Object is null + * + * @see ToStringExclude + * @since 2.1 + */ + public static String toString(final Object object, final ToStringStyle style, final boolean outputTransients, final boolean outputStatics) { + return toString(object, style, outputTransients, outputStatics, null); + } + + /** + *

+ * Builds a toString value through reflection. + *

+ * + *

+ * It uses AccessibleObject.setAccessible to gain access to private fields. This means that it will + * throw a security exception if run under a security manager, if the permissions are not set up correctly. It is + * also not as efficient as testing explicitly. + *

+ * + *

+ * If the outputTransients is true, transient fields will be output, otherwise they + * are ignored, as they are likely derived fields, and not part of the value of the Object. + *

+ * + *

+ * If the outputStatics is true, static fields will be output, otherwise they are + * ignored. + *

+ * + *

+ * Superclass fields will be appended up to and including the specified superclass. A null superclass is treated as + * java.lang.Object. + *

+ * + *

+ * If the style is null, the default ToStringStyle is used. + *

+ * + * @param + * the type of the object + * @param object + * the Object to be output + * @param style + * the style of the toString to create, may be null + * @param outputTransients + * whether to include transient fields + * @param outputStatics + * whether to include static fields + * @param reflectUpToClass + * the superclass to reflect up to (inclusive), may be null + * @return the String result + * @throws IllegalArgumentException + * if the Object is null + * + * @see ToStringExclude + * @since 2.1 + */ + public static String toString( + final T object, final ToStringStyle style, final boolean outputTransients, + final boolean outputStatics, final Class reflectUpToClass) { + return new ReflectionToStringBuilder(object, style, null, reflectUpToClass, outputTransients, outputStatics) + .toString(); + } + + /** + * Builds a String for a toString method excluding the given field names. + * + * @param object + * The object to "toString". + * @param excludeFieldNames + * The field names to exclude. Null excludes nothing. + * @return The toString value. + */ + public static String toStringExclude(final Object object, final Collection excludeFieldNames) { + return toStringExclude(object, toNoNullStringArray(excludeFieldNames)); + } + + /** + * Converts the given Collection into an array of Strings. The returned array does not contain null + * entries. Note that {@link Arrays#sort(Object[])} will throw an {@link NullPointerException} if an array element + * is null. + * + * @param collection + * The collection to convert + * @return A new array of Strings. + */ +/** + * Converts the given Collection into an array of Strings. The returned array does not contain null + * entries. Note that {@link Arrays#sort(Object[])} will throw an {@link NullPointerException} if an array element + * is null. + * + * @param collection + * The collection to convert + * @return A new array of Strings. + */ +static java.lang.String[] toNoNullStringArray(final java.util.Collection collection) { + { + return org.apache.commons.lang3.builder.ReflectionToStringBuilder.toNoNullStringArray(/* NPEX_NULL_EXP */ + collection.toArray()); + } +} + + /** + * Returns a new array of Strings without null elements. Internal method used to normalize exclude lists + * (arrays and collections). Note that {@link Arrays#sort(Object[])} will throw an {@link NullPointerException} + * if an array element is null. + * + * @param array + * The array to check + * @return The given array or a new array without null. + */ + static String[] toNoNullStringArray(final Object[] array) { + final List list = new ArrayList(array.length); + for (final Object e : array) { + if (e != null) { + list.add(e.toString()); + } + } + return list.toArray(ArrayUtils.EMPTY_STRING_ARRAY); + } + + + /** + * Builds a String for a toString method excluding the given field names. + * + * @param object + * The object to "toString". + * @param excludeFieldNames + * The field names to exclude + * @return The toString value. + */ + public static String toStringExclude(final Object object, final String... excludeFieldNames) { + return new ReflectionToStringBuilder(object).setExcludeFieldNames(excludeFieldNames).toString(); + } + + private static Object checkNotNull(final Object obj) { + if (obj == null) { + throw new IllegalArgumentException("The Object passed in should not be null."); + } + return obj; + } + + /** + * Whether or not to append static fields. + */ + private boolean appendStatics = false; + + /** + * Whether or not to append transient fields. + */ + private boolean appendTransients = false; + + /** + * Which field names to exclude from output. Intended for fields like "password". + * + * @since 3.0 this is protected instead of private + */ + protected String[] excludeFieldNames; + + /** + * The last super class to stop appending fields for. + */ + private Class upToClass = null; + + /** + *

+ * Constructor. + *

+ * + *

+ * This constructor outputs using the default style set with setDefaultStyle. + *

+ * + * @param object + * the Object to build a toString for, must not be null + * @throws IllegalArgumentException + * if the Object passed in is null + */ + public ReflectionToStringBuilder(final Object object) { + super(checkNotNull(object)); + } + + /** + *

+ * Constructor. + *

+ * + *

+ * If the style is null, the default style is used. + *

+ * + * @param object + * the Object to build a toString for, must not be null + * @param style + * the style of the toString to create, may be null + * @throws IllegalArgumentException + * if the Object passed in is null + */ + public ReflectionToStringBuilder(final Object object, final ToStringStyle style) { + super(checkNotNull(object), style); + } + + /** + *

+ * Constructor. + *

+ * + *

+ * If the style is null, the default style is used. + *

+ * + *

+ * If the buffer is null, a new one is created. + *

+ * + * @param object + * the Object to build a toString for + * @param style + * the style of the toString to create, may be null + * @param buffer + * the StringBuffer to populate, may be null + * @throws IllegalArgumentException + * if the Object passed in is null + */ + public ReflectionToStringBuilder(final Object object, final ToStringStyle style, final StringBuffer buffer) { + super(checkNotNull(object), style, buffer); + } + + /** + * Constructor. + * + * @param + * the type of the object + * @param object + * the Object to build a toString for + * @param style + * the style of the toString to create, may be null + * @param buffer + * the StringBuffer to populate, may be null + * @param reflectUpToClass + * the superclass to reflect up to (inclusive), may be null + * @param outputTransients + * whether to include transient fields + * @param outputStatics + * whether to include static fields + * @since 2.1 + */ + public ReflectionToStringBuilder( + final T object, final ToStringStyle style, final StringBuffer buffer, + final Class reflectUpToClass, final boolean outputTransients, final boolean outputStatics) { + super(checkNotNull(object), style, buffer); + this.setUpToClass(reflectUpToClass); + this.setAppendTransients(outputTransients); + this.setAppendStatics(outputStatics); + } + + /** + * Returns whether or not to append the given Field. + *
    + *
  • Transient fields are appended only if {@link #isAppendTransients()} returns true. + *
  • Static fields are appended only if {@link #isAppendStatics()} returns true. + *
  • Inner class fields are not appended.
  • + *
+ * + * @param field + * The Field to test. + * @return Whether or not to append the given Field. + */ + protected boolean accept(final Field field) { + if (field.getName().indexOf(ClassUtils.INNER_CLASS_SEPARATOR_CHAR) != -1) { + // Reject field from inner class. + return false; + } + if (Modifier.isTransient(field.getModifiers()) && !this.isAppendTransients()) { + // Reject transient fields. + return false; + } + if (Modifier.isStatic(field.getModifiers()) && !this.isAppendStatics()) { + // Reject static fields. + return false; + } + if (this.excludeFieldNames != null + && Arrays.binarySearch(this.excludeFieldNames, field.getName()) >= 0) { + // Reject fields from the getExcludeFieldNames list. + return false; + } + if(field.isAnnotationPresent(ToStringExclude.class)) { + return false; + } + return true; + } + + /** + *

+ * Appends the fields and values defined by the given object of the given Class. + *

+ * + *

+ * If a cycle is detected as an object is "toString()'ed", such an object is rendered as if + * Object.toString() had been called and not implemented by the object. + *

+ * + * @param clazz + * The class of object parameter + */ + protected void appendFieldsIn(final Class clazz) { + if (clazz.isArray()) { + this.reflectionAppendArray(this.getObject()); + return; + } + final Field[] fields = clazz.getDeclaredFields(); + AccessibleObject.setAccessible(fields, true); + for (final Field field : fields) { + final String fieldName = field.getName(); + if (this.accept(field)) { + try { + // Warning: Field.get(Object) creates wrappers objects + // for primitive types. + final Object fieldValue = this.getValue(field); + this.append(fieldName, fieldValue); + } catch (final IllegalAccessException ex) { + //this can't happen. Would get a Security exception + // instead + //throw a runtime exception in case the impossible + // happens. + throw new InternalError("Unexpected IllegalAccessException: " + ex.getMessage()); + } + } + } + } + + /** + * @return Returns the excludeFieldNames. + */ + public String[] getExcludeFieldNames() { + return this.excludeFieldNames.clone(); + } + + /** + *

+ * Gets the last super class to stop appending fields for. + *

+ * + * @return The last super class to stop appending fields for. + */ + public Class getUpToClass() { + return this.upToClass; + } + + /** + *

+ * Calls java.lang.reflect.Field.get(Object). + *

+ * + * @param field + * The Field to query. + * @return The Object from the given Field. + * + * @throws IllegalArgumentException + * see {@link java.lang.reflect.Field#get(Object)} + * @throws IllegalAccessException + * see {@link java.lang.reflect.Field#get(Object)} + * + * @see java.lang.reflect.Field#get(Object) + */ + protected Object getValue(final Field field) throws IllegalArgumentException, IllegalAccessException { + return field.get(this.getObject()); + } + + /** + *

+ * Gets whether or not to append static fields. + *

+ * + * @return Whether or not to append static fields. + * @since 2.1 + */ + public boolean isAppendStatics() { + return this.appendStatics; + } + + /** + *

+ * Gets whether or not to append transient fields. + *

+ * + * @return Whether or not to append transient fields. + */ + public boolean isAppendTransients() { + return this.appendTransients; + } + + /** + *

+ * Append to the toString an Object array. + *

+ * + * @param array + * the array to add to the toString + * @return this + */ + public ReflectionToStringBuilder reflectionAppendArray(final Object array) { + this.getStyle().reflectionAppendArrayDetail(this.getStringBuffer(), null, array); + return this; + } + + /** + *

+ * Sets whether or not to append static fields. + *

+ * + * @param appendStatics + * Whether or not to append static fields. + * @since 2.1 + */ + public void setAppendStatics(final boolean appendStatics) { + this.appendStatics = appendStatics; + } + + /** + *

+ * Sets whether or not to append transient fields. + *

+ * + * @param appendTransients + * Whether or not to append transient fields. + */ + public void setAppendTransients(final boolean appendTransients) { + this.appendTransients = appendTransients; + } + + /** + * Sets the field names to exclude. + * + * @param excludeFieldNamesParam + * The excludeFieldNames to excluding from toString or null. + * @return this + */ + public ReflectionToStringBuilder setExcludeFieldNames(final String... excludeFieldNamesParam) { + if (excludeFieldNamesParam == null) { + this.excludeFieldNames = null; + } else { + //clone and remove nulls + this.excludeFieldNames = toNoNullStringArray(excludeFieldNamesParam); + Arrays.sort(this.excludeFieldNames); + } + return this; + } + + /** + *

+ * Sets the last super class to stop appending fields for. + *

+ * + * @param clazz + * The last super class to stop appending fields for. + */ + public void setUpToClass(final Class clazz) { + if (clazz != null) { + final Object object = getObject(); + if (object != null && clazz.isInstance(object) == false) { + throw new IllegalArgumentException("Specified class is not a superclass of the object"); + } + } + this.upToClass = clazz; + } + + /** + *

+ * Gets the String built by this builder. + *

+ * + * @return the built string + */ + @Override + public String toString() { + if (this.getObject() == null) { + return this.getStyle().getNullText(); + } + Class clazz = this.getObject().getClass(); + this.appendFieldsIn(clazz); + while (clazz.getSuperclass() != null && clazz != this.getUpToClass()) { + clazz = clazz.getSuperclass(); + this.appendFieldsIn(clazz); + } + return super.toString(); + } + +} diff --git a/Java/commons-lang-ReflectionToStringBuilder_327/metadata.json b/Java/commons-lang-ReflectionToStringBuilder_327/metadata.json new file mode 100644 index 000000000..97aec1f42 --- /dev/null +++ b/Java/commons-lang-ReflectionToStringBuilder_327/metadata.json @@ -0,0 +1,21 @@ +{ + "language": "java", + "id": "commons-lang-ReflectionToStringBuilder_327", + "buggyPath": ".", + "referencePath": null, + "buildCommand": "mvn package -V -B -Denforcer.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true -Drat.skip=true -Dlicense.skip=true -Dfindbugs.skip=true -Dgpg.skip=true -Dskip.npm=true -Dskip.gulp=true -Dskip.bower=true -Drat.numUnapprovedLicenses=100 -DskipTests=true -DskipITs=true -Dtest=None -DfailIfNoTests=false", + "testCommand": "mvn test -V -B -Denforcer.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true -Drat.skip=true -Dlicense.skip=true -Dfindbugs.skip=true -Dgpg.skip=true -Dskip.npm=true -Dskip.gulp=true -Dskip.bower=true -Drat.numUnapprovedLicenses=100", + "categories": [ + "safety", + "npe" + ], + "npe": { + "filepath": "src/main/java/org/apache/commons/lang3/builder/ReflectionToStringBuilder.java", + "line": 338, + "npe_method": "toNoNullStringArray", + "deref_field": "collection", + "npe_class": "ReflectionToStringBuilder", + "repo": "commons-lang", + "bug_id": "ReflectionToStringBuilder_327" + } +} diff --git a/Java/commons-lang-ReflectionToStringBuilder_327/npe.json b/Java/commons-lang-ReflectionToStringBuilder_327/npe.json new file mode 100644 index 000000000..4cff57bf1 --- /dev/null +++ b/Java/commons-lang-ReflectionToStringBuilder_327/npe.json @@ -0,0 +1,7 @@ +{ + "filepath": "src/main/java/org/apache/commons/lang3/builder/ReflectionToStringBuilder.java", + "line": 338, + "npe_method": "toNoNullStringArray", + "deref_field": "collection", + "npe_class": "ReflectionToStringBuilder" +} \ No newline at end of file diff --git a/Java/commons-lang-ReflectionToStringBuilder_345/Dockerfile b/Java/commons-lang-ReflectionToStringBuilder_345/Dockerfile new file mode 100644 index 000000000..7b7fbe349 --- /dev/null +++ b/Java/commons-lang-ReflectionToStringBuilder_345/Dockerfile @@ -0,0 +1,18 @@ +FROM ghcr.io/kupl/starlab-benchmarks/java-base:commons-lang + +ENV TZ=Asia/Seoul + +COPY ./metadata.json . +COPY ./npe.json . +COPY ./buggy.java /tmp/buggy.java +RUN export BUGGY_PATH=$(cat metadata.json | jq -r ".npe.filepath") \ + && export BUGGY_LINE=$(cat metadata.json | jq -r ".npe.line") \ + && export BUGGY_MTHD=$(cat metadata.json | jq -r ".npe.npe_method") \ + && mv /tmp/buggy.java $BUGGY_PATH \ + && echo "[{\"filepath\": \"$BUGGY_PATH\", \"line\": $BUGGY_LINE, \"method_name\": \"$BUGGY_MTHD\"}]" | jq . > traces.json + +RUN git init . && git add -A + +RUN $(cat metadata.json | jq -r ".buildCommand") + +RUN $(cat metadata.json | jq -r ".testCommand"); if [ $? -eq 0 ]; then exit 1; fi diff --git a/Java/commons-lang-ReflectionToStringBuilder_345/buggy.java b/Java/commons-lang-ReflectionToStringBuilder_345/buggy.java new file mode 100644 index 000000000..b60e662b1 --- /dev/null +++ b/Java/commons-lang-ReflectionToStringBuilder_345/buggy.java @@ -0,0 +1,729 @@ +/* + * 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.reflect.AccessibleObject; +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; + +import org.apache.commons.lang3.ArrayUtils; +import org.apache.commons.lang3.ClassUtils; + +/** + *

+ * Assists in implementing {@link Object#toString()} methods using reflection. + *

+ *

+ * This class uses reflection to determine the fields to append. Because these fields are usually private, the class + * uses {@link java.lang.reflect.AccessibleObject#setAccessible(java.lang.reflect.AccessibleObject[], boolean)} to + * change the visibility of the fields. This will fail under a security manager, unless the appropriate permissions are + * set up correctly. + *

+ *

+ * Using reflection to access (private) fields circumvents any synchronization protection guarding access to these + * fields. If a toString method cannot safely read a field, you should exclude it from the toString method, or use + * synchronization consistent with the class' lock management around the invocation of the method. Take special care to + * exclude non-thread-safe collection classes, because these classes may throw ConcurrentModificationException if + * modified while the toString method is executing. + *

+ *

+ * A typical invocation for this method would look like: + *

+ *
+ * public String toString() {
+ *     return ReflectionToStringBuilder.toString(this);
+ * }
+ * 
+ *

+ * You can also use the builder to debug 3rd party objects: + *

+ *
+ * System.out.println("An object: " + ReflectionToStringBuilder.toString(anObject));
+ * 
+ *

+ * A subclass can control field output by overriding the methods: + *

+ *
    + *
  • {@link #accept(java.lang.reflect.Field)}
  • + *
  • {@link #getValue(java.lang.reflect.Field)}
  • + *
+ *

+ * For example, this method does not include the password field in the returned String: + *

+ *
+ * public String toString() {
+ *     return (new ReflectionToStringBuilder(this) {
+ *         protected boolean accept(Field f) {
+ *             return super.accept(f) && !f.getName().equals("password");
+ *         }
+ *     }).toString();
+ * }
+ * 
+ *

+ * Alternatively the {@link ToStringExclude} annotation can be used to exclude fields from being incorporated in the + * result. + *

+ *

+ * The exact format of the toString is determined by the {@link ToStringStyle} passed into the constructor. + *

+ * + *

+ * Note: the default {@link ToStringStyle} will only do a "shallow" formatting, i.e. composed objects are not + * further traversed. To get "deep" formatting, use an instance of {@link RecursiveToStringStyle}. + *

+ * + * @since 2.0 + */ +public class ReflectionToStringBuilder extends ToStringBuilder { + + /** + *

+ * Builds a toString value using the default ToStringStyle through reflection. + *

+ * + *

+ * It uses AccessibleObject.setAccessible to gain access to private fields. This means that it will + * throw a security exception if run under a security manager, if the permissions are not set up correctly. It is + * also not as efficient as testing explicitly. + *

+ * + *

+ * Transient members will be not be included, as they are likely derived. Static fields will not be included. + * Superclass fields will be appended. + *

+ * + * @param object + * the Object to be output + * @return the String result + * @throws IllegalArgumentException + * if the Object is null + * + * @see ToStringExclude + */ + public static String toString(final Object object) { + return toString(object, null, false, false, null); + } + + /** + *

+ * Builds a toString value through reflection. + *

+ * + *

+ * It uses AccessibleObject.setAccessible to gain access to private fields. This means that it will + * throw a security exception if run under a security manager, if the permissions are not set up correctly. It is + * also not as efficient as testing explicitly. + *

+ * + *

+ * Transient members will be not be included, as they are likely derived. Static fields will not be included. + * Superclass fields will be appended. + *

+ * + *

+ * If the style is null, the default ToStringStyle is used. + *

+ * + * @param object + * the Object to be output + * @param style + * the style of the toString to create, may be null + * @return the String result + * @throws IllegalArgumentException + * if the Object or ToStringStyle is null + * + * @see ToStringExclude + */ + public static String toString(final Object object, final ToStringStyle style) { + return toString(object, style, false, false, null); + } + + /** + *

+ * Builds a toString value through reflection. + *

+ * + *

+ * It uses AccessibleObject.setAccessible to gain access to private fields. This means that it will + * throw a security exception if run under a security manager, if the permissions are not set up correctly. It is + * also not as efficient as testing explicitly. + *

+ * + *

+ * If the outputTransients is true, transient members will be output, otherwise they + * are ignored, as they are likely derived fields, and not part of the value of the Object. + *

+ * + *

+ * Static fields will not be included. Superclass fields will be appended. + *

+ * + *

+ * If the style is null, the default ToStringStyle is used. + *

+ * + * @param object + * the Object to be output + * @param style + * the style of the toString to create, may be null + * @param outputTransients + * whether to include transient fields + * @return the String result + * @throws IllegalArgumentException + * if the Object is null + * + * @see ToStringExclude + */ + public static String toString(final Object object, final ToStringStyle style, final boolean outputTransients) { + return toString(object, style, outputTransients, false, null); + } + + /** + *

+ * Builds a toString value through reflection. + *

+ * + *

+ * It uses AccessibleObject.setAccessible to gain access to private fields. This means that it will + * throw a security exception if run under a security manager, if the permissions are not set up correctly. It is + * also not as efficient as testing explicitly. + *

+ * + *

+ * If the outputTransients is true, transient fields will be output, otherwise they + * are ignored, as they are likely derived fields, and not part of the value of the Object. + *

+ * + *

+ * If the outputStatics is true, static fields will be output, otherwise they are + * ignored. + *

+ * + *

+ * Static fields will not be included. Superclass fields will be appended. + *

+ * + *

+ * If the style is null, the default ToStringStyle is used. + *

+ * + * @param object + * the Object to be output + * @param style + * the style of the toString to create, may be null + * @param outputTransients + * whether to include transient fields + * @param outputStatics + * whether to include static fields + * @return the String result + * @throws IllegalArgumentException + * if the Object is null + * + * @see ToStringExclude + * @since 2.1 + */ + public static String toString(final Object object, final ToStringStyle style, final boolean outputTransients, final boolean outputStatics) { + return toString(object, style, outputTransients, outputStatics, null); + } + + /** + *

+ * Builds a toString value through reflection. + *

+ * + *

+ * It uses AccessibleObject.setAccessible to gain access to private fields. This means that it will + * throw a security exception if run under a security manager, if the permissions are not set up correctly. It is + * also not as efficient as testing explicitly. + *

+ * + *

+ * If the outputTransients is true, transient fields will be output, otherwise they + * are ignored, as they are likely derived fields, and not part of the value of the Object. + *

+ * + *

+ * If the outputStatics is true, static fields will be output, otherwise they are + * ignored. + *

+ * + *

+ * Superclass fields will be appended up to and including the specified superclass. A null superclass is treated as + * java.lang.Object. + *

+ * + *

+ * If the style is null, the default ToStringStyle is used. + *

+ * + * @param + * the type of the object + * @param object + * the Object to be output + * @param style + * the style of the toString to create, may be null + * @param outputTransients + * whether to include transient fields + * @param outputStatics + * whether to include static fields + * @param reflectUpToClass + * the superclass to reflect up to (inclusive), may be null + * @return the String result + * @throws IllegalArgumentException + * if the Object is null + * + * @see ToStringExclude + * @since 2.1 + */ + public static String toString( + final T object, final ToStringStyle style, final boolean outputTransients, + final boolean outputStatics, final Class reflectUpToClass) { + return new ReflectionToStringBuilder(object, style, null, reflectUpToClass, outputTransients, outputStatics) + .toString(); + } + + /** + * Builds a String for a toString method excluding the given field names. + * + * @param object + * The object to "toString". + * @param excludeFieldNames + * The field names to exclude. Null excludes nothing. + * @return The toString value. + */ + public static String toStringExclude(final Object object, final Collection excludeFieldNames) { + return toStringExclude(object, toNoNullStringArray(excludeFieldNames)); + } + + /** + * Converts the given Collection into an array of Strings. The returned array does not contain null + * entries. Note that {@link Arrays#sort(Object[])} will throw an {@link NullPointerException} if an array element + * is null. + * + * @param collection + * The collection to convert + * @return A new array of Strings. + */ + static String[] toNoNullStringArray(final Collection collection) { + if (collection == null) { + return ArrayUtils.EMPTY_STRING_ARRAY; + } + return toNoNullStringArray(collection.toArray()); + } + + /** + * Returns a new array of Strings without null elements. Internal method used to normalize exclude lists + * (arrays and collections). Note that {@link Arrays#sort(Object[])} will throw an {@link NullPointerException} + * if an array element is null. + * + * @param array + * The array to check + * @return The given array or a new array without null. + */ +/** + * Returns a new array of Strings without null elements. Internal method used to normalize exclude lists + * (arrays and collections). Note that {@link Arrays#sort(Object[])} will throw an {@link NullPointerException} + * if an array element is null. + * + * @param array + * The array to check + * @return The given array or a new array without null. + */ +static java.lang.String[] toNoNullStringArray(final java.lang.Object[] array) { + final java.util.List list = new java.util.ArrayList(array.length); + for (final java.lang.Object e : array) { + { + list.add(/* NPEX_NULL_EXP */ + e.toString()); + } + } + return list.toArray(org.apache.commons.lang3.ArrayUtils.EMPTY_STRING_ARRAY); +} + + + /** + * Builds a String for a toString method excluding the given field names. + * + * @param object + * The object to "toString". + * @param excludeFieldNames + * The field names to exclude + * @return The toString value. + */ + public static String toStringExclude(final Object object, final String... excludeFieldNames) { + return new ReflectionToStringBuilder(object).setExcludeFieldNames(excludeFieldNames).toString(); + } + + private static Object checkNotNull(final Object obj) { + if (obj == null) { + throw new IllegalArgumentException("The Object passed in should not be null."); + } + return obj; + } + + /** + * Whether or not to append static fields. + */ + private boolean appendStatics = false; + + /** + * Whether or not to append transient fields. + */ + private boolean appendTransients = false; + + /** + * Which field names to exclude from output. Intended for fields like "password". + * + * @since 3.0 this is protected instead of private + */ + protected String[] excludeFieldNames; + + /** + * The last super class to stop appending fields for. + */ + private Class upToClass = null; + + /** + *

+ * Constructor. + *

+ * + *

+ * This constructor outputs using the default style set with setDefaultStyle. + *

+ * + * @param object + * the Object to build a toString for, must not be null + * @throws IllegalArgumentException + * if the Object passed in is null + */ + public ReflectionToStringBuilder(final Object object) { + super(checkNotNull(object)); + } + + /** + *

+ * Constructor. + *

+ * + *

+ * If the style is null, the default style is used. + *

+ * + * @param object + * the Object to build a toString for, must not be null + * @param style + * the style of the toString to create, may be null + * @throws IllegalArgumentException + * if the Object passed in is null + */ + public ReflectionToStringBuilder(final Object object, final ToStringStyle style) { + super(checkNotNull(object), style); + } + + /** + *

+ * Constructor. + *

+ * + *

+ * If the style is null, the default style is used. + *

+ * + *

+ * If the buffer is null, a new one is created. + *

+ * + * @param object + * the Object to build a toString for + * @param style + * the style of the toString to create, may be null + * @param buffer + * the StringBuffer to populate, may be null + * @throws IllegalArgumentException + * if the Object passed in is null + */ + public ReflectionToStringBuilder(final Object object, final ToStringStyle style, final StringBuffer buffer) { + super(checkNotNull(object), style, buffer); + } + + /** + * Constructor. + * + * @param + * the type of the object + * @param object + * the Object to build a toString for + * @param style + * the style of the toString to create, may be null + * @param buffer + * the StringBuffer to populate, may be null + * @param reflectUpToClass + * the superclass to reflect up to (inclusive), may be null + * @param outputTransients + * whether to include transient fields + * @param outputStatics + * whether to include static fields + * @since 2.1 + */ + public ReflectionToStringBuilder( + final T object, final ToStringStyle style, final StringBuffer buffer, + final Class reflectUpToClass, final boolean outputTransients, final boolean outputStatics) { + super(checkNotNull(object), style, buffer); + this.setUpToClass(reflectUpToClass); + this.setAppendTransients(outputTransients); + this.setAppendStatics(outputStatics); + } + + /** + * Returns whether or not to append the given Field. + *
    + *
  • Transient fields are appended only if {@link #isAppendTransients()} returns true. + *
  • Static fields are appended only if {@link #isAppendStatics()} returns true. + *
  • Inner class fields are not appended.
  • + *
+ * + * @param field + * The Field to test. + * @return Whether or not to append the given Field. + */ + protected boolean accept(final Field field) { + if (field.getName().indexOf(ClassUtils.INNER_CLASS_SEPARATOR_CHAR) != -1) { + // Reject field from inner class. + return false; + } + if (Modifier.isTransient(field.getModifiers()) && !this.isAppendTransients()) { + // Reject transient fields. + return false; + } + if (Modifier.isStatic(field.getModifiers()) && !this.isAppendStatics()) { + // Reject static fields. + return false; + } + if (this.excludeFieldNames != null + && Arrays.binarySearch(this.excludeFieldNames, field.getName()) >= 0) { + // Reject fields from the getExcludeFieldNames list. + return false; + } + if(field.isAnnotationPresent(ToStringExclude.class)) { + return false; + } + return true; + } + + /** + *

+ * Appends the fields and values defined by the given object of the given Class. + *

+ * + *

+ * If a cycle is detected as an object is "toString()'ed", such an object is rendered as if + * Object.toString() had been called and not implemented by the object. + *

+ * + * @param clazz + * The class of object parameter + */ + protected void appendFieldsIn(final Class clazz) { + if (clazz.isArray()) { + this.reflectionAppendArray(this.getObject()); + return; + } + final Field[] fields = clazz.getDeclaredFields(); + AccessibleObject.setAccessible(fields, true); + for (final Field field : fields) { + final String fieldName = field.getName(); + if (this.accept(field)) { + try { + // Warning: Field.get(Object) creates wrappers objects + // for primitive types. + final Object fieldValue = this.getValue(field); + this.append(fieldName, fieldValue); + } catch (final IllegalAccessException ex) { + //this can't happen. Would get a Security exception + // instead + //throw a runtime exception in case the impossible + // happens. + throw new InternalError("Unexpected IllegalAccessException: " + ex.getMessage()); + } + } + } + } + + /** + * @return Returns the excludeFieldNames. + */ + public String[] getExcludeFieldNames() { + return this.excludeFieldNames.clone(); + } + + /** + *

+ * Gets the last super class to stop appending fields for. + *

+ * + * @return The last super class to stop appending fields for. + */ + public Class getUpToClass() { + return this.upToClass; + } + + /** + *

+ * Calls java.lang.reflect.Field.get(Object). + *

+ * + * @param field + * The Field to query. + * @return The Object from the given Field. + * + * @throws IllegalArgumentException + * see {@link java.lang.reflect.Field#get(Object)} + * @throws IllegalAccessException + * see {@link java.lang.reflect.Field#get(Object)} + * + * @see java.lang.reflect.Field#get(Object) + */ + protected Object getValue(final Field field) throws IllegalArgumentException, IllegalAccessException { + return field.get(this.getObject()); + } + + /** + *

+ * Gets whether or not to append static fields. + *

+ * + * @return Whether or not to append static fields. + * @since 2.1 + */ + public boolean isAppendStatics() { + return this.appendStatics; + } + + /** + *

+ * Gets whether or not to append transient fields. + *

+ * + * @return Whether or not to append transient fields. + */ + public boolean isAppendTransients() { + return this.appendTransients; + } + + /** + *

+ * Append to the toString an Object array. + *

+ * + * @param array + * the array to add to the toString + * @return this + */ + public ReflectionToStringBuilder reflectionAppendArray(final Object array) { + this.getStyle().reflectionAppendArrayDetail(this.getStringBuffer(), null, array); + return this; + } + + /** + *

+ * Sets whether or not to append static fields. + *

+ * + * @param appendStatics + * Whether or not to append static fields. + * @since 2.1 + */ + public void setAppendStatics(final boolean appendStatics) { + this.appendStatics = appendStatics; + } + + /** + *

+ * Sets whether or not to append transient fields. + *

+ * + * @param appendTransients + * Whether or not to append transient fields. + */ + public void setAppendTransients(final boolean appendTransients) { + this.appendTransients = appendTransients; + } + + /** + * Sets the field names to exclude. + * + * @param excludeFieldNamesParam + * The excludeFieldNames to excluding from toString or null. + * @return this + */ + public ReflectionToStringBuilder setExcludeFieldNames(final String... excludeFieldNamesParam) { + if (excludeFieldNamesParam == null) { + this.excludeFieldNames = null; + } else { + //clone and remove nulls + this.excludeFieldNames = toNoNullStringArray(excludeFieldNamesParam); + Arrays.sort(this.excludeFieldNames); + } + return this; + } + + /** + *

+ * Sets the last super class to stop appending fields for. + *

+ * + * @param clazz + * The last super class to stop appending fields for. + */ + public void setUpToClass(final Class clazz) { + if (clazz != null) { + final Object object = getObject(); + if (object != null && clazz.isInstance(object) == false) { + throw new IllegalArgumentException("Specified class is not a superclass of the object"); + } + } + this.upToClass = clazz; + } + + /** + *

+ * Gets the String built by this builder. + *

+ * + * @return the built string + */ + @Override + public String toString() { + if (this.getObject() == null) { + return this.getStyle().getNullText(); + } + Class clazz = this.getObject().getClass(); + this.appendFieldsIn(clazz); + while (clazz.getSuperclass() != null && clazz != this.getUpToClass()) { + clazz = clazz.getSuperclass(); + this.appendFieldsIn(clazz); + } + return super.toString(); + } + +} diff --git a/Java/commons-lang-ReflectionToStringBuilder_345/metadata.json b/Java/commons-lang-ReflectionToStringBuilder_345/metadata.json new file mode 100644 index 000000000..d5ddaa6be --- /dev/null +++ b/Java/commons-lang-ReflectionToStringBuilder_345/metadata.json @@ -0,0 +1,21 @@ +{ + "language": "java", + "id": "commons-lang-ReflectionToStringBuilder_345", + "buggyPath": ".", + "referencePath": null, + "buildCommand": "mvn package -V -B -Denforcer.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true -Drat.skip=true -Dlicense.skip=true -Dfindbugs.skip=true -Dgpg.skip=true -Dskip.npm=true -Dskip.gulp=true -Dskip.bower=true -Drat.numUnapprovedLicenses=100 -DskipTests=true -DskipITs=true -Dtest=None -DfailIfNoTests=false", + "testCommand": "mvn test -V -B -Denforcer.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true -Drat.skip=true -Dlicense.skip=true -Dfindbugs.skip=true -Dgpg.skip=true -Dskip.npm=true -Dskip.gulp=true -Dskip.bower=true -Drat.numUnapprovedLicenses=100", + "categories": [ + "safety", + "npe" + ], + "npe": { + "filepath": "src/main/java/org/apache/commons/lang3/builder/ReflectionToStringBuilder.java", + "line": 356, + "npe_method": "toNoNullStringArray", + "deref_field": "e", + "npe_class": "ReflectionToStringBuilder", + "repo": "commons-lang", + "bug_id": "ReflectionToStringBuilder_345" + } +} diff --git a/Java/commons-lang-ReflectionToStringBuilder_345/npe.json b/Java/commons-lang-ReflectionToStringBuilder_345/npe.json new file mode 100644 index 000000000..47b0c5d91 --- /dev/null +++ b/Java/commons-lang-ReflectionToStringBuilder_345/npe.json @@ -0,0 +1,7 @@ +{ + "filepath": "src/main/java/org/apache/commons/lang3/builder/ReflectionToStringBuilder.java", + "line": 356, + "npe_method": "toNoNullStringArray", + "deref_field": "e", + "npe_class": "ReflectionToStringBuilder" +} \ No newline at end of file diff --git a/Java/commons-lang-ReflectionToStringBuilder_367/Dockerfile b/Java/commons-lang-ReflectionToStringBuilder_367/Dockerfile new file mode 100644 index 000000000..7b7fbe349 --- /dev/null +++ b/Java/commons-lang-ReflectionToStringBuilder_367/Dockerfile @@ -0,0 +1,18 @@ +FROM ghcr.io/kupl/starlab-benchmarks/java-base:commons-lang + +ENV TZ=Asia/Seoul + +COPY ./metadata.json . +COPY ./npe.json . +COPY ./buggy.java /tmp/buggy.java +RUN export BUGGY_PATH=$(cat metadata.json | jq -r ".npe.filepath") \ + && export BUGGY_LINE=$(cat metadata.json | jq -r ".npe.line") \ + && export BUGGY_MTHD=$(cat metadata.json | jq -r ".npe.npe_method") \ + && mv /tmp/buggy.java $BUGGY_PATH \ + && echo "[{\"filepath\": \"$BUGGY_PATH\", \"line\": $BUGGY_LINE, \"method_name\": \"$BUGGY_MTHD\"}]" | jq . > traces.json + +RUN git init . && git add -A + +RUN $(cat metadata.json | jq -r ".buildCommand") + +RUN $(cat metadata.json | jq -r ".testCommand"); if [ $? -eq 0 ]; then exit 1; fi diff --git a/Java/commons-lang-ReflectionToStringBuilder_367/buggy.java b/Java/commons-lang-ReflectionToStringBuilder_367/buggy.java new file mode 100644 index 000000000..685c6007f --- /dev/null +++ b/Java/commons-lang-ReflectionToStringBuilder_367/buggy.java @@ -0,0 +1,719 @@ +/* + * 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.reflect.AccessibleObject; +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; + +import org.apache.commons.lang3.ArrayUtils; +import org.apache.commons.lang3.ClassUtils; + +/** + *

+ * Assists in implementing {@link Object#toString()} methods using reflection. + *

+ *

+ * This class uses reflection to determine the fields to append. Because these fields are usually private, the class + * uses {@link java.lang.reflect.AccessibleObject#setAccessible(java.lang.reflect.AccessibleObject[], boolean)} to + * change the visibility of the fields. This will fail under a security manager, unless the appropriate permissions are + * set up correctly. + *

+ *

+ * Using reflection to access (private) fields circumvents any synchronization protection guarding access to these + * fields. If a toString method cannot safely read a field, you should exclude it from the toString method, or use + * synchronization consistent with the class' lock management around the invocation of the method. Take special care to + * exclude non-thread-safe collection classes, because these classes may throw ConcurrentModificationException if + * modified while the toString method is executing. + *

+ *

+ * A typical invocation for this method would look like: + *

+ *
+ * public String toString() {
+ *     return ReflectionToStringBuilder.toString(this);
+ * }
+ * 
+ *

+ * You can also use the builder to debug 3rd party objects: + *

+ *
+ * System.out.println("An object: " + ReflectionToStringBuilder.toString(anObject));
+ * 
+ *

+ * A subclass can control field output by overriding the methods: + *

+ *
    + *
  • {@link #accept(java.lang.reflect.Field)}
  • + *
  • {@link #getValue(java.lang.reflect.Field)}
  • + *
+ *

+ * For example, this method does not include the password field in the returned String: + *

+ *
+ * public String toString() {
+ *     return (new ReflectionToStringBuilder(this) {
+ *         protected boolean accept(Field f) {
+ *             return super.accept(f) && !f.getName().equals("password");
+ *         }
+ *     }).toString();
+ * }
+ * 
+ *

+ * Alternatively the {@link ToStringExclude} annotation can be used to exclude fields from being incorporated in the + * result. + *

+ *

+ * The exact format of the toString is determined by the {@link ToStringStyle} passed into the constructor. + *

+ * + *

+ * Note: the default {@link ToStringStyle} will only do a "shallow" formatting, i.e. composed objects are not + * further traversed. To get "deep" formatting, use an instance of {@link RecursiveToStringStyle}. + *

+ * + * @since 2.0 + */ +public class ReflectionToStringBuilder extends ToStringBuilder { + + /** + *

+ * Builds a toString value using the default ToStringStyle through reflection. + *

+ * + *

+ * It uses AccessibleObject.setAccessible to gain access to private fields. This means that it will + * throw a security exception if run under a security manager, if the permissions are not set up correctly. It is + * also not as efficient as testing explicitly. + *

+ * + *

+ * Transient members will be not be included, as they are likely derived. Static fields will not be included. + * Superclass fields will be appended. + *

+ * + * @param object + * the Object to be output + * @return the String result + * @throws IllegalArgumentException + * if the Object is null + * + * @see ToStringExclude + */ + public static String toString(final Object object) { + return toString(object, null, false, false, null); + } + + /** + *

+ * Builds a toString value through reflection. + *

+ * + *

+ * It uses AccessibleObject.setAccessible to gain access to private fields. This means that it will + * throw a security exception if run under a security manager, if the permissions are not set up correctly. It is + * also not as efficient as testing explicitly. + *

+ * + *

+ * Transient members will be not be included, as they are likely derived. Static fields will not be included. + * Superclass fields will be appended. + *

+ * + *

+ * If the style is null, the default ToStringStyle is used. + *

+ * + * @param object + * the Object to be output + * @param style + * the style of the toString to create, may be null + * @return the String result + * @throws IllegalArgumentException + * if the Object or ToStringStyle is null + * + * @see ToStringExclude + */ + public static String toString(final Object object, final ToStringStyle style) { + return toString(object, style, false, false, null); + } + + /** + *

+ * Builds a toString value through reflection. + *

+ * + *

+ * It uses AccessibleObject.setAccessible to gain access to private fields. This means that it will + * throw a security exception if run under a security manager, if the permissions are not set up correctly. It is + * also not as efficient as testing explicitly. + *

+ * + *

+ * If the outputTransients is true, transient members will be output, otherwise they + * are ignored, as they are likely derived fields, and not part of the value of the Object. + *

+ * + *

+ * Static fields will not be included. Superclass fields will be appended. + *

+ * + *

+ * If the style is null, the default ToStringStyle is used. + *

+ * + * @param object + * the Object to be output + * @param style + * the style of the toString to create, may be null + * @param outputTransients + * whether to include transient fields + * @return the String result + * @throws IllegalArgumentException + * if the Object is null + * + * @see ToStringExclude + */ + public static String toString(final Object object, final ToStringStyle style, final boolean outputTransients) { + return toString(object, style, outputTransients, false, null); + } + + /** + *

+ * Builds a toString value through reflection. + *

+ * + *

+ * It uses AccessibleObject.setAccessible to gain access to private fields. This means that it will + * throw a security exception if run under a security manager, if the permissions are not set up correctly. It is + * also not as efficient as testing explicitly. + *

+ * + *

+ * If the outputTransients is true, transient fields will be output, otherwise they + * are ignored, as they are likely derived fields, and not part of the value of the Object. + *

+ * + *

+ * If the outputStatics is true, static fields will be output, otherwise they are + * ignored. + *

+ * + *

+ * Static fields will not be included. Superclass fields will be appended. + *

+ * + *

+ * If the style is null, the default ToStringStyle is used. + *

+ * + * @param object + * the Object to be output + * @param style + * the style of the toString to create, may be null + * @param outputTransients + * whether to include transient fields + * @param outputStatics + * whether to include static fields + * @return the String result + * @throws IllegalArgumentException + * if the Object is null + * + * @see ToStringExclude + * @since 2.1 + */ + public static String toString(final Object object, final ToStringStyle style, final boolean outputTransients, final boolean outputStatics) { + return toString(object, style, outputTransients, outputStatics, null); + } + + /** + *

+ * Builds a toString value through reflection. + *

+ * + *

+ * It uses AccessibleObject.setAccessible to gain access to private fields. This means that it will + * throw a security exception if run under a security manager, if the permissions are not set up correctly. It is + * also not as efficient as testing explicitly. + *

+ * + *

+ * If the outputTransients is true, transient fields will be output, otherwise they + * are ignored, as they are likely derived fields, and not part of the value of the Object. + *

+ * + *

+ * If the outputStatics is true, static fields will be output, otherwise they are + * ignored. + *

+ * + *

+ * Superclass fields will be appended up to and including the specified superclass. A null superclass is treated as + * java.lang.Object. + *

+ * + *

+ * If the style is null, the default ToStringStyle is used. + *

+ * + * @param + * the type of the object + * @param object + * the Object to be output + * @param style + * the style of the toString to create, may be null + * @param outputTransients + * whether to include transient fields + * @param outputStatics + * whether to include static fields + * @param reflectUpToClass + * the superclass to reflect up to (inclusive), may be null + * @return the String result + * @throws IllegalArgumentException + * if the Object is null + * + * @see ToStringExclude + * @since 2.1 + */ + public static String toString( + final T object, final ToStringStyle style, final boolean outputTransients, + final boolean outputStatics, final Class reflectUpToClass) { + return new ReflectionToStringBuilder(object, style, null, reflectUpToClass, outputTransients, outputStatics) + .toString(); + } + + /** + * Builds a String for a toString method excluding the given field names. + * + * @param object + * The object to "toString". + * @param excludeFieldNames + * The field names to exclude. Null excludes nothing. + * @return The toString value. + */ + public static String toStringExclude(final Object object, final Collection excludeFieldNames) { + return toStringExclude(object, toNoNullStringArray(excludeFieldNames)); + } + + /** + * Converts the given Collection into an array of Strings. The returned array does not contain null + * entries. Note that {@link Arrays#sort(Object[])} will throw an {@link NullPointerException} if an array element + * is null. + * + * @param collection + * The collection to convert + * @return A new array of Strings. + */ + static String[] toNoNullStringArray(final Collection collection) { + if (collection == null) { + return ArrayUtils.EMPTY_STRING_ARRAY; + } + return toNoNullStringArray(collection.toArray()); + } + + /** + * Returns a new array of Strings without null elements. Internal method used to normalize exclude lists + * (arrays and collections). Note that {@link Arrays#sort(Object[])} will throw an {@link NullPointerException} + * if an array element is null. + * + * @param array + * The array to check + * @return The given array or a new array without null. + */ + static String[] toNoNullStringArray(final Object[] array) { + final List list = new ArrayList(array.length); + for (final Object e : array) { + if (e != null) { + list.add(e.toString()); + } + } + return list.toArray(ArrayUtils.EMPTY_STRING_ARRAY); + } + + + /** + * Builds a String for a toString method excluding the given field names. + * + * @param object + * The object to "toString". + * @param excludeFieldNames + * The field names to exclude + * @return The toString value. + */ + public static String toStringExclude(final Object object, final String... excludeFieldNames) { + return new ReflectionToStringBuilder(object).setExcludeFieldNames(excludeFieldNames).toString(); + } + +private static java.lang.Object checkNotNull(final java.lang.Object obj) { + { + return /* NPEX_NULL_EXP */ + obj; + } +} + + /** + * Whether or not to append static fields. + */ + private boolean appendStatics = false; + + /** + * Whether or not to append transient fields. + */ + private boolean appendTransients = false; + + /** + * Which field names to exclude from output. Intended for fields like "password". + * + * @since 3.0 this is protected instead of private + */ + protected String[] excludeFieldNames; + + /** + * The last super class to stop appending fields for. + */ + private Class upToClass = null; + + /** + *

+ * Constructor. + *

+ * + *

+ * This constructor outputs using the default style set with setDefaultStyle. + *

+ * + * @param object + * the Object to build a toString for, must not be null + * @throws IllegalArgumentException + * if the Object passed in is null + */ + public ReflectionToStringBuilder(final Object object) { + super(checkNotNull(object)); + } + + /** + *

+ * Constructor. + *

+ * + *

+ * If the style is null, the default style is used. + *

+ * + * @param object + * the Object to build a toString for, must not be null + * @param style + * the style of the toString to create, may be null + * @throws IllegalArgumentException + * if the Object passed in is null + */ + public ReflectionToStringBuilder(final Object object, final ToStringStyle style) { + super(checkNotNull(object), style); + } + + /** + *

+ * Constructor. + *

+ * + *

+ * If the style is null, the default style is used. + *

+ * + *

+ * If the buffer is null, a new one is created. + *

+ * + * @param object + * the Object to build a toString for + * @param style + * the style of the toString to create, may be null + * @param buffer + * the StringBuffer to populate, may be null + * @throws IllegalArgumentException + * if the Object passed in is null + */ + public ReflectionToStringBuilder(final Object object, final ToStringStyle style, final StringBuffer buffer) { + super(checkNotNull(object), style, buffer); + } + + /** + * Constructor. + * + * @param + * the type of the object + * @param object + * the Object to build a toString for + * @param style + * the style of the toString to create, may be null + * @param buffer + * the StringBuffer to populate, may be null + * @param reflectUpToClass + * the superclass to reflect up to (inclusive), may be null + * @param outputTransients + * whether to include transient fields + * @param outputStatics + * whether to include static fields + * @since 2.1 + */ + public ReflectionToStringBuilder( + final T object, final ToStringStyle style, final StringBuffer buffer, + final Class reflectUpToClass, final boolean outputTransients, final boolean outputStatics) { + super(checkNotNull(object), style, buffer); + this.setUpToClass(reflectUpToClass); + this.setAppendTransients(outputTransients); + this.setAppendStatics(outputStatics); + } + + /** + * Returns whether or not to append the given Field. + *
    + *
  • Transient fields are appended only if {@link #isAppendTransients()} returns true. + *
  • Static fields are appended only if {@link #isAppendStatics()} returns true. + *
  • Inner class fields are not appended.
  • + *
+ * + * @param field + * The Field to test. + * @return Whether or not to append the given Field. + */ + protected boolean accept(final Field field) { + if (field.getName().indexOf(ClassUtils.INNER_CLASS_SEPARATOR_CHAR) != -1) { + // Reject field from inner class. + return false; + } + if (Modifier.isTransient(field.getModifiers()) && !this.isAppendTransients()) { + // Reject transient fields. + return false; + } + if (Modifier.isStatic(field.getModifiers()) && !this.isAppendStatics()) { + // Reject static fields. + return false; + } + if (this.excludeFieldNames != null + && Arrays.binarySearch(this.excludeFieldNames, field.getName()) >= 0) { + // Reject fields from the getExcludeFieldNames list. + return false; + } + if(field.isAnnotationPresent(ToStringExclude.class)) { + return false; + } + return true; + } + + /** + *

+ * Appends the fields and values defined by the given object of the given Class. + *

+ * + *

+ * If a cycle is detected as an object is "toString()'ed", such an object is rendered as if + * Object.toString() had been called and not implemented by the object. + *

+ * + * @param clazz + * The class of object parameter + */ + protected void appendFieldsIn(final Class clazz) { + if (clazz.isArray()) { + this.reflectionAppendArray(this.getObject()); + return; + } + final Field[] fields = clazz.getDeclaredFields(); + AccessibleObject.setAccessible(fields, true); + for (final Field field : fields) { + final String fieldName = field.getName(); + if (this.accept(field)) { + try { + // Warning: Field.get(Object) creates wrappers objects + // for primitive types. + final Object fieldValue = this.getValue(field); + this.append(fieldName, fieldValue); + } catch (final IllegalAccessException ex) { + //this can't happen. Would get a Security exception + // instead + //throw a runtime exception in case the impossible + // happens. + throw new InternalError("Unexpected IllegalAccessException: " + ex.getMessage()); + } + } + } + } + + /** + * @return Returns the excludeFieldNames. + */ + public String[] getExcludeFieldNames() { + return this.excludeFieldNames.clone(); + } + + /** + *

+ * Gets the last super class to stop appending fields for. + *

+ * + * @return The last super class to stop appending fields for. + */ + public Class getUpToClass() { + return this.upToClass; + } + + /** + *

+ * Calls java.lang.reflect.Field.get(Object). + *

+ * + * @param field + * The Field to query. + * @return The Object from the given Field. + * + * @throws IllegalArgumentException + * see {@link java.lang.reflect.Field#get(Object)} + * @throws IllegalAccessException + * see {@link java.lang.reflect.Field#get(Object)} + * + * @see java.lang.reflect.Field#get(Object) + */ + protected Object getValue(final Field field) throws IllegalArgumentException, IllegalAccessException { + return field.get(this.getObject()); + } + + /** + *

+ * Gets whether or not to append static fields. + *

+ * + * @return Whether or not to append static fields. + * @since 2.1 + */ + public boolean isAppendStatics() { + return this.appendStatics; + } + + /** + *

+ * Gets whether or not to append transient fields. + *

+ * + * @return Whether or not to append transient fields. + */ + public boolean isAppendTransients() { + return this.appendTransients; + } + + /** + *

+ * Append to the toString an Object array. + *

+ * + * @param array + * the array to add to the toString + * @return this + */ + public ReflectionToStringBuilder reflectionAppendArray(final Object array) { + this.getStyle().reflectionAppendArrayDetail(this.getStringBuffer(), null, array); + return this; + } + + /** + *

+ * Sets whether or not to append static fields. + *

+ * + * @param appendStatics + * Whether or not to append static fields. + * @since 2.1 + */ + public void setAppendStatics(final boolean appendStatics) { + this.appendStatics = appendStatics; + } + + /** + *

+ * Sets whether or not to append transient fields. + *

+ * + * @param appendTransients + * Whether or not to append transient fields. + */ + public void setAppendTransients(final boolean appendTransients) { + this.appendTransients = appendTransients; + } + + /** + * Sets the field names to exclude. + * + * @param excludeFieldNamesParam + * The excludeFieldNames to excluding from toString or null. + * @return this + */ + public ReflectionToStringBuilder setExcludeFieldNames(final String... excludeFieldNamesParam) { + if (excludeFieldNamesParam == null) { + this.excludeFieldNames = null; + } else { + //clone and remove nulls + this.excludeFieldNames = toNoNullStringArray(excludeFieldNamesParam); + Arrays.sort(this.excludeFieldNames); + } + return this; + } + + /** + *

+ * Sets the last super class to stop appending fields for. + *

+ * + * @param clazz + * The last super class to stop appending fields for. + */ + public void setUpToClass(final Class clazz) { + if (clazz != null) { + final Object object = getObject(); + if (object != null && clazz.isInstance(object) == false) { + throw new IllegalArgumentException("Specified class is not a superclass of the object"); + } + } + this.upToClass = clazz; + } + + /** + *

+ * Gets the String built by this builder. + *

+ * + * @return the built string + */ + @Override + public String toString() { + if (this.getObject() == null) { + return this.getStyle().getNullText(); + } + Class clazz = this.getObject().getClass(); + this.appendFieldsIn(clazz); + while (clazz.getSuperclass() != null && clazz != this.getUpToClass()) { + clazz = clazz.getSuperclass(); + this.appendFieldsIn(clazz); + } + return super.toString(); + } + +} diff --git a/Java/commons-lang-ReflectionToStringBuilder_367/metadata.json b/Java/commons-lang-ReflectionToStringBuilder_367/metadata.json new file mode 100644 index 000000000..1427c233d --- /dev/null +++ b/Java/commons-lang-ReflectionToStringBuilder_367/metadata.json @@ -0,0 +1,21 @@ +{ + "language": "java", + "id": "commons-lang-ReflectionToStringBuilder_367", + "buggyPath": ".", + "referencePath": null, + "buildCommand": "mvn package -V -B -Denforcer.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true -Drat.skip=true -Dlicense.skip=true -Dfindbugs.skip=true -Dgpg.skip=true -Dskip.npm=true -Dskip.gulp=true -Dskip.bower=true -Drat.numUnapprovedLicenses=100 -DskipTests=true -DskipITs=true -Dtest=None -DfailIfNoTests=false", + "testCommand": "mvn test -V -B -Denforcer.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true -Drat.skip=true -Dlicense.skip=true -Dfindbugs.skip=true -Dgpg.skip=true -Dskip.npm=true -Dskip.gulp=true -Dskip.bower=true -Drat.numUnapprovedLicenses=100", + "categories": [ + "safety", + "npe" + ], + "npe": { + "filepath": "src/main/java/org/apache/commons/lang3/builder/ReflectionToStringBuilder.java", + "line": 369, + "npe_method": "checkNotNull", + "deref_field": "obj", + "npe_class": "ReflectionToStringBuilder", + "repo": "commons-lang", + "bug_id": "ReflectionToStringBuilder_367" + } +} diff --git a/Java/commons-lang-ReflectionToStringBuilder_367/npe.json b/Java/commons-lang-ReflectionToStringBuilder_367/npe.json new file mode 100644 index 000000000..c70f3621b --- /dev/null +++ b/Java/commons-lang-ReflectionToStringBuilder_367/npe.json @@ -0,0 +1,7 @@ +{ + "filepath": "src/main/java/org/apache/commons/lang3/builder/ReflectionToStringBuilder.java", + "line": 369, + "npe_method": "checkNotNull", + "deref_field": "obj", + "npe_class": "ReflectionToStringBuilder" +} \ No newline at end of file diff --git a/Java/commons-lang-ReflectionToStringBuilder_670/Dockerfile b/Java/commons-lang-ReflectionToStringBuilder_670/Dockerfile new file mode 100644 index 000000000..7b7fbe349 --- /dev/null +++ b/Java/commons-lang-ReflectionToStringBuilder_670/Dockerfile @@ -0,0 +1,18 @@ +FROM ghcr.io/kupl/starlab-benchmarks/java-base:commons-lang + +ENV TZ=Asia/Seoul + +COPY ./metadata.json . +COPY ./npe.json . +COPY ./buggy.java /tmp/buggy.java +RUN export BUGGY_PATH=$(cat metadata.json | jq -r ".npe.filepath") \ + && export BUGGY_LINE=$(cat metadata.json | jq -r ".npe.line") \ + && export BUGGY_MTHD=$(cat metadata.json | jq -r ".npe.npe_method") \ + && mv /tmp/buggy.java $BUGGY_PATH \ + && echo "[{\"filepath\": \"$BUGGY_PATH\", \"line\": $BUGGY_LINE, \"method_name\": \"$BUGGY_MTHD\"}]" | jq . > traces.json + +RUN git init . && git add -A + +RUN $(cat metadata.json | jq -r ".buildCommand") + +RUN $(cat metadata.json | jq -r ".testCommand"); if [ $? -eq 0 ]; then exit 1; fi diff --git a/Java/commons-lang-ReflectionToStringBuilder_670/buggy.java b/Java/commons-lang-ReflectionToStringBuilder_670/buggy.java new file mode 100644 index 000000000..2be9ffda1 --- /dev/null +++ b/Java/commons-lang-ReflectionToStringBuilder_670/buggy.java @@ -0,0 +1,725 @@ +/* + * 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.reflect.AccessibleObject; +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; + +import org.apache.commons.lang3.ArrayUtils; +import org.apache.commons.lang3.ClassUtils; + +/** + *

+ * Assists in implementing {@link Object#toString()} methods using reflection. + *

+ *

+ * This class uses reflection to determine the fields to append. Because these fields are usually private, the class + * uses {@link java.lang.reflect.AccessibleObject#setAccessible(java.lang.reflect.AccessibleObject[], boolean)} to + * change the visibility of the fields. This will fail under a security manager, unless the appropriate permissions are + * set up correctly. + *

+ *

+ * Using reflection to access (private) fields circumvents any synchronization protection guarding access to these + * fields. If a toString method cannot safely read a field, you should exclude it from the toString method, or use + * synchronization consistent with the class' lock management around the invocation of the method. Take special care to + * exclude non-thread-safe collection classes, because these classes may throw ConcurrentModificationException if + * modified while the toString method is executing. + *

+ *

+ * A typical invocation for this method would look like: + *

+ *
+ * public String toString() {
+ *     return ReflectionToStringBuilder.toString(this);
+ * }
+ * 
+ *

+ * You can also use the builder to debug 3rd party objects: + *

+ *
+ * System.out.println("An object: " + ReflectionToStringBuilder.toString(anObject));
+ * 
+ *

+ * A subclass can control field output by overriding the methods: + *

+ *
    + *
  • {@link #accept(java.lang.reflect.Field)}
  • + *
  • {@link #getValue(java.lang.reflect.Field)}
  • + *
+ *

+ * For example, this method does not include the password field in the returned String: + *

+ *
+ * public String toString() {
+ *     return (new ReflectionToStringBuilder(this) {
+ *         protected boolean accept(Field f) {
+ *             return super.accept(f) && !f.getName().equals("password");
+ *         }
+ *     }).toString();
+ * }
+ * 
+ *

+ * Alternatively the {@link ToStringExclude} annotation can be used to exclude fields from being incorporated in the + * result. + *

+ *

+ * The exact format of the toString is determined by the {@link ToStringStyle} passed into the constructor. + *

+ * + *

+ * Note: the default {@link ToStringStyle} will only do a "shallow" formatting, i.e. composed objects are not + * further traversed. To get "deep" formatting, use an instance of {@link RecursiveToStringStyle}. + *

+ * + * @since 2.0 + */ +public class ReflectionToStringBuilder extends ToStringBuilder { + + /** + *

+ * Builds a toString value using the default ToStringStyle through reflection. + *

+ * + *

+ * It uses AccessibleObject.setAccessible to gain access to private fields. This means that it will + * throw a security exception if run under a security manager, if the permissions are not set up correctly. It is + * also not as efficient as testing explicitly. + *

+ * + *

+ * Transient members will be not be included, as they are likely derived. Static fields will not be included. + * Superclass fields will be appended. + *

+ * + * @param object + * the Object to be output + * @return the String result + * @throws IllegalArgumentException + * if the Object is null + * + * @see ToStringExclude + */ + public static String toString(final Object object) { + return toString(object, null, false, false, null); + } + + /** + *

+ * Builds a toString value through reflection. + *

+ * + *

+ * It uses AccessibleObject.setAccessible to gain access to private fields. This means that it will + * throw a security exception if run under a security manager, if the permissions are not set up correctly. It is + * also not as efficient as testing explicitly. + *

+ * + *

+ * Transient members will be not be included, as they are likely derived. Static fields will not be included. + * Superclass fields will be appended. + *

+ * + *

+ * If the style is null, the default ToStringStyle is used. + *

+ * + * @param object + * the Object to be output + * @param style + * the style of the toString to create, may be null + * @return the String result + * @throws IllegalArgumentException + * if the Object or ToStringStyle is null + * + * @see ToStringExclude + */ + public static String toString(final Object object, final ToStringStyle style) { + return toString(object, style, false, false, null); + } + + /** + *

+ * Builds a toString value through reflection. + *

+ * + *

+ * It uses AccessibleObject.setAccessible to gain access to private fields. This means that it will + * throw a security exception if run under a security manager, if the permissions are not set up correctly. It is + * also not as efficient as testing explicitly. + *

+ * + *

+ * If the outputTransients is true, transient members will be output, otherwise they + * are ignored, as they are likely derived fields, and not part of the value of the Object. + *

+ * + *

+ * Static fields will not be included. Superclass fields will be appended. + *

+ * + *

+ * If the style is null, the default ToStringStyle is used. + *

+ * + * @param object + * the Object to be output + * @param style + * the style of the toString to create, may be null + * @param outputTransients + * whether to include transient fields + * @return the String result + * @throws IllegalArgumentException + * if the Object is null + * + * @see ToStringExclude + */ + public static String toString(final Object object, final ToStringStyle style, final boolean outputTransients) { + return toString(object, style, outputTransients, false, null); + } + + /** + *

+ * Builds a toString value through reflection. + *

+ * + *

+ * It uses AccessibleObject.setAccessible to gain access to private fields. This means that it will + * throw a security exception if run under a security manager, if the permissions are not set up correctly. It is + * also not as efficient as testing explicitly. + *

+ * + *

+ * If the outputTransients is true, transient fields will be output, otherwise they + * are ignored, as they are likely derived fields, and not part of the value of the Object. + *

+ * + *

+ * If the outputStatics is true, static fields will be output, otherwise they are + * ignored. + *

+ * + *

+ * Static fields will not be included. Superclass fields will be appended. + *

+ * + *

+ * If the style is null, the default ToStringStyle is used. + *

+ * + * @param object + * the Object to be output + * @param style + * the style of the toString to create, may be null + * @param outputTransients + * whether to include transient fields + * @param outputStatics + * whether to include static fields + * @return the String result + * @throws IllegalArgumentException + * if the Object is null + * + * @see ToStringExclude + * @since 2.1 + */ + public static String toString(final Object object, final ToStringStyle style, final boolean outputTransients, final boolean outputStatics) { + return toString(object, style, outputTransients, outputStatics, null); + } + + /** + *

+ * Builds a toString value through reflection. + *

+ * + *

+ * It uses AccessibleObject.setAccessible to gain access to private fields. This means that it will + * throw a security exception if run under a security manager, if the permissions are not set up correctly. It is + * also not as efficient as testing explicitly. + *

+ * + *

+ * If the outputTransients is true, transient fields will be output, otherwise they + * are ignored, as they are likely derived fields, and not part of the value of the Object. + *

+ * + *

+ * If the outputStatics is true, static fields will be output, otherwise they are + * ignored. + *

+ * + *

+ * Superclass fields will be appended up to and including the specified superclass. A null superclass is treated as + * java.lang.Object. + *

+ * + *

+ * If the style is null, the default ToStringStyle is used. + *

+ * + * @param + * the type of the object + * @param object + * the Object to be output + * @param style + * the style of the toString to create, may be null + * @param outputTransients + * whether to include transient fields + * @param outputStatics + * whether to include static fields + * @param reflectUpToClass + * the superclass to reflect up to (inclusive), may be null + * @return the String result + * @throws IllegalArgumentException + * if the Object is null + * + * @see ToStringExclude + * @since 2.1 + */ + public static String toString( + final T object, final ToStringStyle style, final boolean outputTransients, + final boolean outputStatics, final Class reflectUpToClass) { + return new ReflectionToStringBuilder(object, style, null, reflectUpToClass, outputTransients, outputStatics) + .toString(); + } + + /** + * Builds a String for a toString method excluding the given field names. + * + * @param object + * The object to "toString". + * @param excludeFieldNames + * The field names to exclude. Null excludes nothing. + * @return The toString value. + */ + public static String toStringExclude(final Object object, final Collection excludeFieldNames) { + return toStringExclude(object, toNoNullStringArray(excludeFieldNames)); + } + + /** + * Converts the given Collection into an array of Strings. The returned array does not contain null + * entries. Note that {@link Arrays#sort(Object[])} will throw an {@link NullPointerException} if an array element + * is null. + * + * @param collection + * The collection to convert + * @return A new array of Strings. + */ + static String[] toNoNullStringArray(final Collection collection) { + if (collection == null) { + return ArrayUtils.EMPTY_STRING_ARRAY; + } + return toNoNullStringArray(collection.toArray()); + } + + /** + * Returns a new array of Strings without null elements. Internal method used to normalize exclude lists + * (arrays and collections). Note that {@link Arrays#sort(Object[])} will throw an {@link NullPointerException} + * if an array element is null. + * + * @param array + * The array to check + * @return The given array or a new array without null. + */ + static String[] toNoNullStringArray(final Object[] array) { + final List list = new ArrayList(array.length); + for (final Object e : array) { + if (e != null) { + list.add(e.toString()); + } + } + return list.toArray(ArrayUtils.EMPTY_STRING_ARRAY); + } + + + /** + * Builds a String for a toString method excluding the given field names. + * + * @param object + * The object to "toString". + * @param excludeFieldNames + * The field names to exclude + * @return The toString value. + */ + public static String toStringExclude(final Object object, final String... excludeFieldNames) { + return new ReflectionToStringBuilder(object).setExcludeFieldNames(excludeFieldNames).toString(); + } + + private static Object checkNotNull(final Object obj) { + if (obj == null) { + throw new IllegalArgumentException("The Object passed in should not be null."); + } + return obj; + } + + /** + * Whether or not to append static fields. + */ + private boolean appendStatics = false; + + /** + * Whether or not to append transient fields. + */ + private boolean appendTransients = false; + + /** + * Which field names to exclude from output. Intended for fields like "password". + * + * @since 3.0 this is protected instead of private + */ + protected String[] excludeFieldNames; + + /** + * The last super class to stop appending fields for. + */ + private Class upToClass = null; + + /** + *

+ * Constructor. + *

+ * + *

+ * This constructor outputs using the default style set with setDefaultStyle. + *

+ * + * @param object + * the Object to build a toString for, must not be null + * @throws IllegalArgumentException + * if the Object passed in is null + */ + public ReflectionToStringBuilder(final Object object) { + super(checkNotNull(object)); + } + + /** + *

+ * Constructor. + *

+ * + *

+ * If the style is null, the default style is used. + *

+ * + * @param object + * the Object to build a toString for, must not be null + * @param style + * the style of the toString to create, may be null + * @throws IllegalArgumentException + * if the Object passed in is null + */ + public ReflectionToStringBuilder(final Object object, final ToStringStyle style) { + super(checkNotNull(object), style); + } + + /** + *

+ * Constructor. + *

+ * + *

+ * If the style is null, the default style is used. + *

+ * + *

+ * If the buffer is null, a new one is created. + *

+ * + * @param object + * the Object to build a toString for + * @param style + * the style of the toString to create, may be null + * @param buffer + * the StringBuffer to populate, may be null + * @throws IllegalArgumentException + * if the Object passed in is null + */ + public ReflectionToStringBuilder(final Object object, final ToStringStyle style, final StringBuffer buffer) { + super(checkNotNull(object), style, buffer); + } + + /** + * Constructor. + * + * @param + * the type of the object + * @param object + * the Object to build a toString for + * @param style + * the style of the toString to create, may be null + * @param buffer + * the StringBuffer to populate, may be null + * @param reflectUpToClass + * the superclass to reflect up to (inclusive), may be null + * @param outputTransients + * whether to include transient fields + * @param outputStatics + * whether to include static fields + * @since 2.1 + */ + public ReflectionToStringBuilder( + final T object, final ToStringStyle style, final StringBuffer buffer, + final Class reflectUpToClass, final boolean outputTransients, final boolean outputStatics) { + super(checkNotNull(object), style, buffer); + this.setUpToClass(reflectUpToClass); + this.setAppendTransients(outputTransients); + this.setAppendStatics(outputStatics); + } + + /** + * Returns whether or not to append the given Field. + *
    + *
  • Transient fields are appended only if {@link #isAppendTransients()} returns true. + *
  • Static fields are appended only if {@link #isAppendStatics()} returns true. + *
  • Inner class fields are not appended.
  • + *
+ * + * @param field + * The Field to test. + * @return Whether or not to append the given Field. + */ + protected boolean accept(final Field field) { + if (field.getName().indexOf(ClassUtils.INNER_CLASS_SEPARATOR_CHAR) != -1) { + // Reject field from inner class. + return false; + } + if (Modifier.isTransient(field.getModifiers()) && !this.isAppendTransients()) { + // Reject transient fields. + return false; + } + if (Modifier.isStatic(field.getModifiers()) && !this.isAppendStatics()) { + // Reject static fields. + return false; + } + if (this.excludeFieldNames != null + && Arrays.binarySearch(this.excludeFieldNames, field.getName()) >= 0) { + // Reject fields from the getExcludeFieldNames list. + return false; + } + if(field.isAnnotationPresent(ToStringExclude.class)) { + return false; + } + return true; + } + + /** + *

+ * Appends the fields and values defined by the given object of the given Class. + *

+ * + *

+ * If a cycle is detected as an object is "toString()'ed", such an object is rendered as if + * Object.toString() had been called and not implemented by the object. + *

+ * + * @param clazz + * The class of object parameter + */ + protected void appendFieldsIn(final Class clazz) { + if (clazz.isArray()) { + this.reflectionAppendArray(this.getObject()); + return; + } + final Field[] fields = clazz.getDeclaredFields(); + AccessibleObject.setAccessible(fields, true); + for (final Field field : fields) { + final String fieldName = field.getName(); + if (this.accept(field)) { + try { + // Warning: Field.get(Object) creates wrappers objects + // for primitive types. + final Object fieldValue = this.getValue(field); + this.append(fieldName, fieldValue); + } catch (final IllegalAccessException ex) { + //this can't happen. Would get a Security exception + // instead + //throw a runtime exception in case the impossible + // happens. + throw new InternalError("Unexpected IllegalAccessException: " + ex.getMessage()); + } + } + } + } + + /** + * @return Returns the excludeFieldNames. + */ + public String[] getExcludeFieldNames() { + return this.excludeFieldNames.clone(); + } + + /** + *

+ * Gets the last super class to stop appending fields for. + *

+ * + * @return The last super class to stop appending fields for. + */ + public Class getUpToClass() { + return this.upToClass; + } + + /** + *

+ * Calls java.lang.reflect.Field.get(Object). + *

+ * + * @param field + * The Field to query. + * @return The Object from the given Field. + * + * @throws IllegalArgumentException + * see {@link java.lang.reflect.Field#get(Object)} + * @throws IllegalAccessException + * see {@link java.lang.reflect.Field#get(Object)} + * + * @see java.lang.reflect.Field#get(Object) + */ + protected Object getValue(final Field field) throws IllegalArgumentException, IllegalAccessException { + return field.get(this.getObject()); + } + + /** + *

+ * Gets whether or not to append static fields. + *

+ * + * @return Whether or not to append static fields. + * @since 2.1 + */ + public boolean isAppendStatics() { + return this.appendStatics; + } + + /** + *

+ * Gets whether or not to append transient fields. + *

+ * + * @return Whether or not to append transient fields. + */ + public boolean isAppendTransients() { + return this.appendTransients; + } + + /** + *

+ * Append to the toString an Object array. + *

+ * + * @param array + * the array to add to the toString + * @return this + */ + public ReflectionToStringBuilder reflectionAppendArray(final Object array) { + this.getStyle().reflectionAppendArrayDetail(this.getStringBuffer(), null, array); + return this; + } + + /** + *

+ * Sets whether or not to append static fields. + *

+ * + * @param appendStatics + * Whether or not to append static fields. + * @since 2.1 + */ + public void setAppendStatics(final boolean appendStatics) { + this.appendStatics = appendStatics; + } + + /** + *

+ * Sets whether or not to append transient fields. + *

+ * + * @param appendTransients + * Whether or not to append transient fields. + */ + public void setAppendTransients(final boolean appendTransients) { + this.appendTransients = appendTransients; + } + + /** + * Sets the field names to exclude. + * + * @param excludeFieldNamesParam + * The excludeFieldNames to excluding from toString or null. + * @return this + */ +/** + * Sets the field names to exclude. + * + * @param excludeFieldNamesParam + * The excludeFieldNames to excluding from toString or null. + * @return this + */ +public org.apache.commons.lang3.builder.ReflectionToStringBuilder setExcludeFieldNames(final java.lang.String... excludeFieldNamesParam) { + { + // clone and remove nulls + this.excludeFieldNames = org.apache.commons.lang3.builder.ReflectionToStringBuilder.toNoNullStringArray(/* NPEX_NULL_EXP */ + excludeFieldNamesParam); + java.util.Arrays.sort(this.excludeFieldNames); + } + return this; +} + + /** + *

+ * Sets the last super class to stop appending fields for. + *

+ * + * @param clazz + * The last super class to stop appending fields for. + */ + public void setUpToClass(final Class clazz) { + if (clazz != null) { + final Object object = getObject(); + if (object != null && clazz.isInstance(object) == false) { + throw new IllegalArgumentException("Specified class is not a superclass of the object"); + } + } + this.upToClass = clazz; + } + + /** + *

+ * Gets the String built by this builder. + *

+ * + * @return the built string + */ + @Override + public String toString() { + if (this.getObject() == null) { + return this.getStyle().getNullText(); + } + Class clazz = this.getObject().getClass(); + this.appendFieldsIn(clazz); + while (clazz.getSuperclass() != null && clazz != this.getUpToClass()) { + clazz = clazz.getSuperclass(); + this.appendFieldsIn(clazz); + } + return super.toString(); + } + +} diff --git a/Java/commons-lang-ReflectionToStringBuilder_670/metadata.json b/Java/commons-lang-ReflectionToStringBuilder_670/metadata.json new file mode 100644 index 000000000..33c2dc8e8 --- /dev/null +++ b/Java/commons-lang-ReflectionToStringBuilder_670/metadata.json @@ -0,0 +1,21 @@ +{ + "language": "java", + "id": "commons-lang-ReflectionToStringBuilder_670", + "buggyPath": ".", + "referencePath": null, + "buildCommand": "mvn package -V -B -Denforcer.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true -Drat.skip=true -Dlicense.skip=true -Dfindbugs.skip=true -Dgpg.skip=true -Dskip.npm=true -Dskip.gulp=true -Dskip.bower=true -Drat.numUnapprovedLicenses=100 -DskipTests=true -DskipITs=true -Dtest=None -DfailIfNoTests=false", + "testCommand": "mvn test -V -B -Denforcer.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true -Drat.skip=true -Dlicense.skip=true -Dfindbugs.skip=true -Dgpg.skip=true -Dskip.npm=true -Dskip.gulp=true -Dskip.bower=true -Drat.numUnapprovedLicenses=100", + "categories": [ + "safety", + "npe" + ], + "npe": { + "filepath": "src/main/java/org/apache/commons/lang3/builder/ReflectionToStringBuilder.java", + "line": 680, + "npe_method": "setExcludeFieldNames", + "deref_field": "excludeFieldNamesParam", + "npe_class": "ReflectionToStringBuilder", + "repo": "commons-lang", + "bug_id": "ReflectionToStringBuilder_670" + } +} diff --git a/Java/commons-lang-ReflectionToStringBuilder_670/npe.json b/Java/commons-lang-ReflectionToStringBuilder_670/npe.json new file mode 100644 index 000000000..fd9421bc0 --- /dev/null +++ b/Java/commons-lang-ReflectionToStringBuilder_670/npe.json @@ -0,0 +1,7 @@ +{ + "filepath": "src/main/java/org/apache/commons/lang3/builder/ReflectionToStringBuilder.java", + "line": 680, + "npe_method": "setExcludeFieldNames", + "deref_field": "excludeFieldNamesParam", + "npe_class": "ReflectionToStringBuilder" +} \ No newline at end of file diff --git a/Java/commons-lang-ReflectionToStringBuilder_689/Dockerfile b/Java/commons-lang-ReflectionToStringBuilder_689/Dockerfile new file mode 100644 index 000000000..7b7fbe349 --- /dev/null +++ b/Java/commons-lang-ReflectionToStringBuilder_689/Dockerfile @@ -0,0 +1,18 @@ +FROM ghcr.io/kupl/starlab-benchmarks/java-base:commons-lang + +ENV TZ=Asia/Seoul + +COPY ./metadata.json . +COPY ./npe.json . +COPY ./buggy.java /tmp/buggy.java +RUN export BUGGY_PATH=$(cat metadata.json | jq -r ".npe.filepath") \ + && export BUGGY_LINE=$(cat metadata.json | jq -r ".npe.line") \ + && export BUGGY_MTHD=$(cat metadata.json | jq -r ".npe.npe_method") \ + && mv /tmp/buggy.java $BUGGY_PATH \ + && echo "[{\"filepath\": \"$BUGGY_PATH\", \"line\": $BUGGY_LINE, \"method_name\": \"$BUGGY_MTHD\"}]" | jq . > traces.json + +RUN git init . && git add -A + +RUN $(cat metadata.json | jq -r ".buildCommand") + +RUN $(cat metadata.json | jq -r ".testCommand"); if [ $? -eq 0 ]; then exit 1; fi diff --git a/Java/commons-lang-ReflectionToStringBuilder_689/buggy.java b/Java/commons-lang-ReflectionToStringBuilder_689/buggy.java new file mode 100644 index 000000000..9fb4d00fd --- /dev/null +++ b/Java/commons-lang-ReflectionToStringBuilder_689/buggy.java @@ -0,0 +1,728 @@ +/* + * 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.reflect.AccessibleObject; +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; + +import org.apache.commons.lang3.ArrayUtils; +import org.apache.commons.lang3.ClassUtils; + +/** + *

+ * Assists in implementing {@link Object#toString()} methods using reflection. + *

+ *

+ * This class uses reflection to determine the fields to append. Because these fields are usually private, the class + * uses {@link java.lang.reflect.AccessibleObject#setAccessible(java.lang.reflect.AccessibleObject[], boolean)} to + * change the visibility of the fields. This will fail under a security manager, unless the appropriate permissions are + * set up correctly. + *

+ *

+ * Using reflection to access (private) fields circumvents any synchronization protection guarding access to these + * fields. If a toString method cannot safely read a field, you should exclude it from the toString method, or use + * synchronization consistent with the class' lock management around the invocation of the method. Take special care to + * exclude non-thread-safe collection classes, because these classes may throw ConcurrentModificationException if + * modified while the toString method is executing. + *

+ *

+ * A typical invocation for this method would look like: + *

+ *
+ * public String toString() {
+ *     return ReflectionToStringBuilder.toString(this);
+ * }
+ * 
+ *

+ * You can also use the builder to debug 3rd party objects: + *

+ *
+ * System.out.println("An object: " + ReflectionToStringBuilder.toString(anObject));
+ * 
+ *

+ * A subclass can control field output by overriding the methods: + *

+ *
    + *
  • {@link #accept(java.lang.reflect.Field)}
  • + *
  • {@link #getValue(java.lang.reflect.Field)}
  • + *
+ *

+ * For example, this method does not include the password field in the returned String: + *

+ *
+ * public String toString() {
+ *     return (new ReflectionToStringBuilder(this) {
+ *         protected boolean accept(Field f) {
+ *             return super.accept(f) && !f.getName().equals("password");
+ *         }
+ *     }).toString();
+ * }
+ * 
+ *

+ * Alternatively the {@link ToStringExclude} annotation can be used to exclude fields from being incorporated in the + * result. + *

+ *

+ * The exact format of the toString is determined by the {@link ToStringStyle} passed into the constructor. + *

+ * + *

+ * Note: the default {@link ToStringStyle} will only do a "shallow" formatting, i.e. composed objects are not + * further traversed. To get "deep" formatting, use an instance of {@link RecursiveToStringStyle}. + *

+ * + * @since 2.0 + */ +public class ReflectionToStringBuilder extends ToStringBuilder { + + /** + *

+ * Builds a toString value using the default ToStringStyle through reflection. + *

+ * + *

+ * It uses AccessibleObject.setAccessible to gain access to private fields. This means that it will + * throw a security exception if run under a security manager, if the permissions are not set up correctly. It is + * also not as efficient as testing explicitly. + *

+ * + *

+ * Transient members will be not be included, as they are likely derived. Static fields will not be included. + * Superclass fields will be appended. + *

+ * + * @param object + * the Object to be output + * @return the String result + * @throws IllegalArgumentException + * if the Object is null + * + * @see ToStringExclude + */ + public static String toString(final Object object) { + return toString(object, null, false, false, null); + } + + /** + *

+ * Builds a toString value through reflection. + *

+ * + *

+ * It uses AccessibleObject.setAccessible to gain access to private fields. This means that it will + * throw a security exception if run under a security manager, if the permissions are not set up correctly. It is + * also not as efficient as testing explicitly. + *

+ * + *

+ * Transient members will be not be included, as they are likely derived. Static fields will not be included. + * Superclass fields will be appended. + *

+ * + *

+ * If the style is null, the default ToStringStyle is used. + *

+ * + * @param object + * the Object to be output + * @param style + * the style of the toString to create, may be null + * @return the String result + * @throws IllegalArgumentException + * if the Object or ToStringStyle is null + * + * @see ToStringExclude + */ + public static String toString(final Object object, final ToStringStyle style) { + return toString(object, style, false, false, null); + } + + /** + *

+ * Builds a toString value through reflection. + *

+ * + *

+ * It uses AccessibleObject.setAccessible to gain access to private fields. This means that it will + * throw a security exception if run under a security manager, if the permissions are not set up correctly. It is + * also not as efficient as testing explicitly. + *

+ * + *

+ * If the outputTransients is true, transient members will be output, otherwise they + * are ignored, as they are likely derived fields, and not part of the value of the Object. + *

+ * + *

+ * Static fields will not be included. Superclass fields will be appended. + *

+ * + *

+ * If the style is null, the default ToStringStyle is used. + *

+ * + * @param object + * the Object to be output + * @param style + * the style of the toString to create, may be null + * @param outputTransients + * whether to include transient fields + * @return the String result + * @throws IllegalArgumentException + * if the Object is null + * + * @see ToStringExclude + */ + public static String toString(final Object object, final ToStringStyle style, final boolean outputTransients) { + return toString(object, style, outputTransients, false, null); + } + + /** + *

+ * Builds a toString value through reflection. + *

+ * + *

+ * It uses AccessibleObject.setAccessible to gain access to private fields. This means that it will + * throw a security exception if run under a security manager, if the permissions are not set up correctly. It is + * also not as efficient as testing explicitly. + *

+ * + *

+ * If the outputTransients is true, transient fields will be output, otherwise they + * are ignored, as they are likely derived fields, and not part of the value of the Object. + *

+ * + *

+ * If the outputStatics is true, static fields will be output, otherwise they are + * ignored. + *

+ * + *

+ * Static fields will not be included. Superclass fields will be appended. + *

+ * + *

+ * If the style is null, the default ToStringStyle is used. + *

+ * + * @param object + * the Object to be output + * @param style + * the style of the toString to create, may be null + * @param outputTransients + * whether to include transient fields + * @param outputStatics + * whether to include static fields + * @return the String result + * @throws IllegalArgumentException + * if the Object is null + * + * @see ToStringExclude + * @since 2.1 + */ + public static String toString(final Object object, final ToStringStyle style, final boolean outputTransients, final boolean outputStatics) { + return toString(object, style, outputTransients, outputStatics, null); + } + + /** + *

+ * Builds a toString value through reflection. + *

+ * + *

+ * It uses AccessibleObject.setAccessible to gain access to private fields. This means that it will + * throw a security exception if run under a security manager, if the permissions are not set up correctly. It is + * also not as efficient as testing explicitly. + *

+ * + *

+ * If the outputTransients is true, transient fields will be output, otherwise they + * are ignored, as they are likely derived fields, and not part of the value of the Object. + *

+ * + *

+ * If the outputStatics is true, static fields will be output, otherwise they are + * ignored. + *

+ * + *

+ * Superclass fields will be appended up to and including the specified superclass. A null superclass is treated as + * java.lang.Object. + *

+ * + *

+ * If the style is null, the default ToStringStyle is used. + *

+ * + * @param + * the type of the object + * @param object + * the Object to be output + * @param style + * the style of the toString to create, may be null + * @param outputTransients + * whether to include transient fields + * @param outputStatics + * whether to include static fields + * @param reflectUpToClass + * the superclass to reflect up to (inclusive), may be null + * @return the String result + * @throws IllegalArgumentException + * if the Object is null + * + * @see ToStringExclude + * @since 2.1 + */ + public static String toString( + final T object, final ToStringStyle style, final boolean outputTransients, + final boolean outputStatics, final Class reflectUpToClass) { + return new ReflectionToStringBuilder(object, style, null, reflectUpToClass, outputTransients, outputStatics) + .toString(); + } + + /** + * Builds a String for a toString method excluding the given field names. + * + * @param object + * The object to "toString". + * @param excludeFieldNames + * The field names to exclude. Null excludes nothing. + * @return The toString value. + */ + public static String toStringExclude(final Object object, final Collection excludeFieldNames) { + return toStringExclude(object, toNoNullStringArray(excludeFieldNames)); + } + + /** + * Converts the given Collection into an array of Strings. The returned array does not contain null + * entries. Note that {@link Arrays#sort(Object[])} will throw an {@link NullPointerException} if an array element + * is null. + * + * @param collection + * The collection to convert + * @return A new array of Strings. + */ + static String[] toNoNullStringArray(final Collection collection) { + if (collection == null) { + return ArrayUtils.EMPTY_STRING_ARRAY; + } + return toNoNullStringArray(collection.toArray()); + } + + /** + * Returns a new array of Strings without null elements. Internal method used to normalize exclude lists + * (arrays and collections). Note that {@link Arrays#sort(Object[])} will throw an {@link NullPointerException} + * if an array element is null. + * + * @param array + * The array to check + * @return The given array or a new array without null. + */ + static String[] toNoNullStringArray(final Object[] array) { + final List list = new ArrayList(array.length); + for (final Object e : array) { + if (e != null) { + list.add(e.toString()); + } + } + return list.toArray(ArrayUtils.EMPTY_STRING_ARRAY); + } + + + /** + * Builds a String for a toString method excluding the given field names. + * + * @param object + * The object to "toString". + * @param excludeFieldNames + * The field names to exclude + * @return The toString value. + */ + public static String toStringExclude(final Object object, final String... excludeFieldNames) { + return new ReflectionToStringBuilder(object).setExcludeFieldNames(excludeFieldNames).toString(); + } + + private static Object checkNotNull(final Object obj) { + if (obj == null) { + throw new IllegalArgumentException("The Object passed in should not be null."); + } + return obj; + } + + /** + * Whether or not to append static fields. + */ + private boolean appendStatics = false; + + /** + * Whether or not to append transient fields. + */ + private boolean appendTransients = false; + + /** + * Which field names to exclude from output. Intended for fields like "password". + * + * @since 3.0 this is protected instead of private + */ + protected String[] excludeFieldNames; + + /** + * The last super class to stop appending fields for. + */ + private Class upToClass = null; + + /** + *

+ * Constructor. + *

+ * + *

+ * This constructor outputs using the default style set with setDefaultStyle. + *

+ * + * @param object + * the Object to build a toString for, must not be null + * @throws IllegalArgumentException + * if the Object passed in is null + */ + public ReflectionToStringBuilder(final Object object) { + super(checkNotNull(object)); + } + + /** + *

+ * Constructor. + *

+ * + *

+ * If the style is null, the default style is used. + *

+ * + * @param object + * the Object to build a toString for, must not be null + * @param style + * the style of the toString to create, may be null + * @throws IllegalArgumentException + * if the Object passed in is null + */ + public ReflectionToStringBuilder(final Object object, final ToStringStyle style) { + super(checkNotNull(object), style); + } + + /** + *

+ * Constructor. + *

+ * + *

+ * If the style is null, the default style is used. + *

+ * + *

+ * If the buffer is null, a new one is created. + *

+ * + * @param object + * the Object to build a toString for + * @param style + * the style of the toString to create, may be null + * @param buffer + * the StringBuffer to populate, may be null + * @throws IllegalArgumentException + * if the Object passed in is null + */ + public ReflectionToStringBuilder(final Object object, final ToStringStyle style, final StringBuffer buffer) { + super(checkNotNull(object), style, buffer); + } + + /** + * Constructor. + * + * @param + * the type of the object + * @param object + * the Object to build a toString for + * @param style + * the style of the toString to create, may be null + * @param buffer + * the StringBuffer to populate, may be null + * @param reflectUpToClass + * the superclass to reflect up to (inclusive), may be null + * @param outputTransients + * whether to include transient fields + * @param outputStatics + * whether to include static fields + * @since 2.1 + */ + public ReflectionToStringBuilder( + final T object, final ToStringStyle style, final StringBuffer buffer, + final Class reflectUpToClass, final boolean outputTransients, final boolean outputStatics) { + super(checkNotNull(object), style, buffer); + this.setUpToClass(reflectUpToClass); + this.setAppendTransients(outputTransients); + this.setAppendStatics(outputStatics); + } + + /** + * Returns whether or not to append the given Field. + *
    + *
  • Transient fields are appended only if {@link #isAppendTransients()} returns true. + *
  • Static fields are appended only if {@link #isAppendStatics()} returns true. + *
  • Inner class fields are not appended.
  • + *
+ * + * @param field + * The Field to test. + * @return Whether or not to append the given Field. + */ + protected boolean accept(final Field field) { + if (field.getName().indexOf(ClassUtils.INNER_CLASS_SEPARATOR_CHAR) != -1) { + // Reject field from inner class. + return false; + } + if (Modifier.isTransient(field.getModifiers()) && !this.isAppendTransients()) { + // Reject transient fields. + return false; + } + if (Modifier.isStatic(field.getModifiers()) && !this.isAppendStatics()) { + // Reject static fields. + return false; + } + if (this.excludeFieldNames != null + && Arrays.binarySearch(this.excludeFieldNames, field.getName()) >= 0) { + // Reject fields from the getExcludeFieldNames list. + return false; + } + if(field.isAnnotationPresent(ToStringExclude.class)) { + return false; + } + return true; + } + + /** + *

+ * Appends the fields and values defined by the given object of the given Class. + *

+ * + *

+ * If a cycle is detected as an object is "toString()'ed", such an object is rendered as if + * Object.toString() had been called and not implemented by the object. + *

+ * + * @param clazz + * The class of object parameter + */ + protected void appendFieldsIn(final Class clazz) { + if (clazz.isArray()) { + this.reflectionAppendArray(this.getObject()); + return; + } + final Field[] fields = clazz.getDeclaredFields(); + AccessibleObject.setAccessible(fields, true); + for (final Field field : fields) { + final String fieldName = field.getName(); + if (this.accept(field)) { + try { + // Warning: Field.get(Object) creates wrappers objects + // for primitive types. + final Object fieldValue = this.getValue(field); + this.append(fieldName, fieldValue); + } catch (final IllegalAccessException ex) { + //this can't happen. Would get a Security exception + // instead + //throw a runtime exception in case the impossible + // happens. + throw new InternalError("Unexpected IllegalAccessException: " + ex.getMessage()); + } + } + } + } + + /** + * @return Returns the excludeFieldNames. + */ + public String[] getExcludeFieldNames() { + return this.excludeFieldNames.clone(); + } + + /** + *

+ * Gets the last super class to stop appending fields for. + *

+ * + * @return The last super class to stop appending fields for. + */ + public Class getUpToClass() { + return this.upToClass; + } + + /** + *

+ * Calls java.lang.reflect.Field.get(Object). + *

+ * + * @param field + * The Field to query. + * @return The Object from the given Field. + * + * @throws IllegalArgumentException + * see {@link java.lang.reflect.Field#get(Object)} + * @throws IllegalAccessException + * see {@link java.lang.reflect.Field#get(Object)} + * + * @see java.lang.reflect.Field#get(Object) + */ + protected Object getValue(final Field field) throws IllegalArgumentException, IllegalAccessException { + return field.get(this.getObject()); + } + + /** + *

+ * Gets whether or not to append static fields. + *

+ * + * @return Whether or not to append static fields. + * @since 2.1 + */ + public boolean isAppendStatics() { + return this.appendStatics; + } + + /** + *

+ * Gets whether or not to append transient fields. + *

+ * + * @return Whether or not to append transient fields. + */ + public boolean isAppendTransients() { + return this.appendTransients; + } + + /** + *

+ * Append to the toString an Object array. + *

+ * + * @param array + * the array to add to the toString + * @return this + */ + public ReflectionToStringBuilder reflectionAppendArray(final Object array) { + this.getStyle().reflectionAppendArrayDetail(this.getStringBuffer(), null, array); + return this; + } + + /** + *

+ * Sets whether or not to append static fields. + *

+ * + * @param appendStatics + * Whether or not to append static fields. + * @since 2.1 + */ + public void setAppendStatics(final boolean appendStatics) { + this.appendStatics = appendStatics; + } + + /** + *

+ * Sets whether or not to append transient fields. + *

+ * + * @param appendTransients + * Whether or not to append transient fields. + */ + public void setAppendTransients(final boolean appendTransients) { + this.appendTransients = appendTransients; + } + + /** + * Sets the field names to exclude. + * + * @param excludeFieldNamesParam + * The excludeFieldNames to excluding from toString or null. + * @return this + */ + public ReflectionToStringBuilder setExcludeFieldNames(final String... excludeFieldNamesParam) { + if (excludeFieldNamesParam == null) { + this.excludeFieldNames = null; + } else { + //clone and remove nulls + this.excludeFieldNames = toNoNullStringArray(excludeFieldNamesParam); + Arrays.sort(this.excludeFieldNames); + } + return this; + } + + /** + *

+ * Sets the last super class to stop appending fields for. + *

+ * + * @param clazz + * The last super class to stop appending fields for. + */ +/** + *

+ * Sets the last super class to stop appending fields for. + *

+ * + * @param clazz + * The last super class to stop appending fields for. + */ +public void setUpToClass(final java.lang.Class clazz) { + { + final java.lang.Object object = getObject(); + if ((object != null) && (/* NPEX_NULL_EXP */ + clazz.isInstance(object) == false)) { + throw new java.lang.IllegalArgumentException("Specified class is not a superclass of the object"); + } + } + this.upToClass = clazz; +} + + /** + *

+ * Gets the String built by this builder. + *

+ * + * @return the built string + */ + @Override + public String toString() { + if (this.getObject() == null) { + return this.getStyle().getNullText(); + } + Class clazz = this.getObject().getClass(); + this.appendFieldsIn(clazz); + while (clazz.getSuperclass() != null && clazz != this.getUpToClass()) { + clazz = clazz.getSuperclass(); + this.appendFieldsIn(clazz); + } + return super.toString(); + } + +} diff --git a/Java/commons-lang-ReflectionToStringBuilder_689/metadata.json b/Java/commons-lang-ReflectionToStringBuilder_689/metadata.json new file mode 100644 index 000000000..48b6799bd --- /dev/null +++ b/Java/commons-lang-ReflectionToStringBuilder_689/metadata.json @@ -0,0 +1,21 @@ +{ + "language": "java", + "id": "commons-lang-ReflectionToStringBuilder_689", + "buggyPath": ".", + "referencePath": null, + "buildCommand": "mvn package -V -B -Denforcer.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true -Drat.skip=true -Dlicense.skip=true -Dfindbugs.skip=true -Dgpg.skip=true -Dskip.npm=true -Dskip.gulp=true -Dskip.bower=true -Drat.numUnapprovedLicenses=100 -DskipTests=true -DskipITs=true -Dtest=None -DfailIfNoTests=false", + "testCommand": "mvn test -V -B -Denforcer.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true -Drat.skip=true -Dlicense.skip=true -Dfindbugs.skip=true -Dgpg.skip=true -Dskip.npm=true -Dskip.gulp=true -Dskip.bower=true -Drat.numUnapprovedLicenses=100", + "categories": [ + "safety", + "npe" + ], + "npe": { + "filepath": "src/main/java/org/apache/commons/lang3/builder/ReflectionToStringBuilder.java", + "line": 700, + "npe_method": "setUpToClass", + "deref_field": "clazz", + "npe_class": "ReflectionToStringBuilder", + "repo": "commons-lang", + "bug_id": "ReflectionToStringBuilder_689" + } +} diff --git a/Java/commons-lang-ReflectionToStringBuilder_689/npe.json b/Java/commons-lang-ReflectionToStringBuilder_689/npe.json new file mode 100644 index 000000000..3f9dddde5 --- /dev/null +++ b/Java/commons-lang-ReflectionToStringBuilder_689/npe.json @@ -0,0 +1,7 @@ +{ + "filepath": "src/main/java/org/apache/commons/lang3/builder/ReflectionToStringBuilder.java", + "line": 700, + "npe_method": "setUpToClass", + "deref_field": "clazz", + "npe_class": "ReflectionToStringBuilder" +} \ No newline at end of file From 4f9681c9a8e8d9950b76d34f7a66bde8d2203f07 Mon Sep 17 00:00:00 2001 From: Seokhyun Lee <7948302+henrylee97@users.noreply.github.com> Date: Fri, 1 Dec 2023 10:16:27 +0900 Subject: [PATCH 4/4] refactor(java): commons-lang O-classes (#143) --- Java/commons-lang-ObjectUtils_121/Dockerfile | 18 + Java/commons-lang-ObjectUtils_121/buggy.java | 1041 +++++++++++++++++ .../metadata.json | 21 + Java/commons-lang-ObjectUtils_121/npe.json | 7 + Java/commons-lang-ObjectUtils_123/Dockerfile | 18 + Java/commons-lang-ObjectUtils_123/buggy.java | 1041 +++++++++++++++++ .../metadata.json | 21 + Java/commons-lang-ObjectUtils_123/npe.json | 7 + Java/commons-lang-ObjectUtils_184/Dockerfile | 18 + Java/commons-lang-ObjectUtils_184/buggy.java | 1040 ++++++++++++++++ .../metadata.json | 21 + Java/commons-lang-ObjectUtils_184/npe.json | 7 + Java/commons-lang-ObjectUtils_272/Dockerfile | 18 + Java/commons-lang-ObjectUtils_272/buggy.java | 1033 ++++++++++++++++ .../metadata.json | 21 + Java/commons-lang-ObjectUtils_272/npe.json | 7 + Java/commons-lang-ObjectUtils_300/Dockerfile | 18 + Java/commons-lang-ObjectUtils_300/buggy.java | 1040 ++++++++++++++++ .../metadata.json | 21 + Java/commons-lang-ObjectUtils_300/npe.json | 7 + Java/commons-lang-ObjectUtils_328/Dockerfile | 18 + Java/commons-lang-ObjectUtils_328/buggy.java | 1035 ++++++++++++++++ .../metadata.json | 21 + Java/commons-lang-ObjectUtils_328/npe.json | 7 + Java/commons-lang-ObjectUtils_457/Dockerfile | 18 + Java/commons-lang-ObjectUtils_457/buggy.java | 1040 ++++++++++++++++ .../metadata.json | 21 + Java/commons-lang-ObjectUtils_457/npe.json | 7 + Java/commons-lang-ObjectUtils_483/Dockerfile | 18 + Java/commons-lang-ObjectUtils_483/buggy.java | 1040 ++++++++++++++++ .../metadata.json | 21 + Java/commons-lang-ObjectUtils_483/npe.json | 7 + Java/commons-lang-ObjectUtils_503/Dockerfile | 18 + Java/commons-lang-ObjectUtils_503/buggy.java | 1033 ++++++++++++++++ .../metadata.json | 21 + Java/commons-lang-ObjectUtils_503/npe.json | 7 + Java/commons-lang-ObjectUtils_528/Dockerfile | 18 + Java/commons-lang-ObjectUtils_528/buggy.java | 1031 ++++++++++++++++ .../metadata.json | 21 + Java/commons-lang-ObjectUtils_528/npe.json | 7 + Java/commons-lang-ObjectUtils_635/Dockerfile | 18 + Java/commons-lang-ObjectUtils_635/buggy.java | 1027 ++++++++++++++++ .../metadata.json | 21 + Java/commons-lang-ObjectUtils_635/npe.json | 7 + Java/commons-lang-ObjectUtils_724/Dockerfile | 18 + Java/commons-lang-ObjectUtils_724/buggy.java | 1036 ++++++++++++++++ .../metadata.json | 21 + Java/commons-lang-ObjectUtils_724/npe.json | 7 + Java/commons-lang-ObjectUtils_95/Dockerfile | 18 + Java/commons-lang-ObjectUtils_95/buggy.java | 1038 ++++++++++++++++ .../commons-lang-ObjectUtils_95/metadata.json | 21 + Java/commons-lang-ObjectUtils_95/npe.json | 7 + 52 files changed, 14073 insertions(+) create mode 100644 Java/commons-lang-ObjectUtils_121/Dockerfile create mode 100644 Java/commons-lang-ObjectUtils_121/buggy.java create mode 100644 Java/commons-lang-ObjectUtils_121/metadata.json create mode 100644 Java/commons-lang-ObjectUtils_121/npe.json create mode 100644 Java/commons-lang-ObjectUtils_123/Dockerfile create mode 100644 Java/commons-lang-ObjectUtils_123/buggy.java create mode 100644 Java/commons-lang-ObjectUtils_123/metadata.json create mode 100644 Java/commons-lang-ObjectUtils_123/npe.json create mode 100644 Java/commons-lang-ObjectUtils_184/Dockerfile create mode 100644 Java/commons-lang-ObjectUtils_184/buggy.java create mode 100644 Java/commons-lang-ObjectUtils_184/metadata.json create mode 100644 Java/commons-lang-ObjectUtils_184/npe.json create mode 100644 Java/commons-lang-ObjectUtils_272/Dockerfile create mode 100644 Java/commons-lang-ObjectUtils_272/buggy.java create mode 100644 Java/commons-lang-ObjectUtils_272/metadata.json create mode 100644 Java/commons-lang-ObjectUtils_272/npe.json create mode 100644 Java/commons-lang-ObjectUtils_300/Dockerfile create mode 100644 Java/commons-lang-ObjectUtils_300/buggy.java create mode 100644 Java/commons-lang-ObjectUtils_300/metadata.json create mode 100644 Java/commons-lang-ObjectUtils_300/npe.json create mode 100644 Java/commons-lang-ObjectUtils_328/Dockerfile create mode 100644 Java/commons-lang-ObjectUtils_328/buggy.java create mode 100644 Java/commons-lang-ObjectUtils_328/metadata.json create mode 100644 Java/commons-lang-ObjectUtils_328/npe.json create mode 100644 Java/commons-lang-ObjectUtils_457/Dockerfile create mode 100644 Java/commons-lang-ObjectUtils_457/buggy.java create mode 100644 Java/commons-lang-ObjectUtils_457/metadata.json create mode 100644 Java/commons-lang-ObjectUtils_457/npe.json create mode 100644 Java/commons-lang-ObjectUtils_483/Dockerfile create mode 100644 Java/commons-lang-ObjectUtils_483/buggy.java create mode 100644 Java/commons-lang-ObjectUtils_483/metadata.json create mode 100644 Java/commons-lang-ObjectUtils_483/npe.json create mode 100644 Java/commons-lang-ObjectUtils_503/Dockerfile create mode 100644 Java/commons-lang-ObjectUtils_503/buggy.java create mode 100644 Java/commons-lang-ObjectUtils_503/metadata.json create mode 100644 Java/commons-lang-ObjectUtils_503/npe.json create mode 100644 Java/commons-lang-ObjectUtils_528/Dockerfile create mode 100644 Java/commons-lang-ObjectUtils_528/buggy.java create mode 100644 Java/commons-lang-ObjectUtils_528/metadata.json create mode 100644 Java/commons-lang-ObjectUtils_528/npe.json create mode 100644 Java/commons-lang-ObjectUtils_635/Dockerfile create mode 100644 Java/commons-lang-ObjectUtils_635/buggy.java create mode 100644 Java/commons-lang-ObjectUtils_635/metadata.json create mode 100644 Java/commons-lang-ObjectUtils_635/npe.json create mode 100644 Java/commons-lang-ObjectUtils_724/Dockerfile create mode 100644 Java/commons-lang-ObjectUtils_724/buggy.java create mode 100644 Java/commons-lang-ObjectUtils_724/metadata.json create mode 100644 Java/commons-lang-ObjectUtils_724/npe.json create mode 100644 Java/commons-lang-ObjectUtils_95/Dockerfile create mode 100644 Java/commons-lang-ObjectUtils_95/buggy.java create mode 100644 Java/commons-lang-ObjectUtils_95/metadata.json create mode 100644 Java/commons-lang-ObjectUtils_95/npe.json diff --git a/Java/commons-lang-ObjectUtils_121/Dockerfile b/Java/commons-lang-ObjectUtils_121/Dockerfile new file mode 100644 index 000000000..7b7fbe349 --- /dev/null +++ b/Java/commons-lang-ObjectUtils_121/Dockerfile @@ -0,0 +1,18 @@ +FROM ghcr.io/kupl/starlab-benchmarks/java-base:commons-lang + +ENV TZ=Asia/Seoul + +COPY ./metadata.json . +COPY ./npe.json . +COPY ./buggy.java /tmp/buggy.java +RUN export BUGGY_PATH=$(cat metadata.json | jq -r ".npe.filepath") \ + && export BUGGY_LINE=$(cat metadata.json | jq -r ".npe.line") \ + && export BUGGY_MTHD=$(cat metadata.json | jq -r ".npe.npe_method") \ + && mv /tmp/buggy.java $BUGGY_PATH \ + && echo "[{\"filepath\": \"$BUGGY_PATH\", \"line\": $BUGGY_LINE, \"method_name\": \"$BUGGY_MTHD\"}]" | jq . > traces.json + +RUN git init . && git add -A + +RUN $(cat metadata.json | jq -r ".buildCommand") + +RUN $(cat metadata.json | jq -r ".testCommand"); if [ $? -eq 0 ]; then exit 1; fi diff --git a/Java/commons-lang-ObjectUtils_121/buggy.java b/Java/commons-lang-ObjectUtils_121/buggy.java new file mode 100644 index 000000000..1f665cff6 --- /dev/null +++ b/Java/commons-lang-ObjectUtils_121/buggy.java @@ -0,0 +1,1041 @@ +/* + * 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.Serializable; +import java.lang.reflect.Array; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.Map; +import java.util.TreeSet; + +import org.apache.commons.lang3.exception.CloneFailedException; +import org.apache.commons.lang3.mutable.MutableInt; +import org.apache.commons.lang3.text.StrBuilder; + +/** + *

Operations on {@code Object}.

+ * + *

This class tries to handle {@code null} input gracefully. + * An exception will generally not be thrown for a {@code null} input. + * Each method documents its behaviour in more detail.

+ * + *

#ThreadSafe#

+ * @since 1.0 + */ +//@Immutable +public class ObjectUtils { + + /** + *

Singleton used as a {@code null} placeholder where + * {@code null} has another meaning.

+ * + *

For example, in a {@code HashMap} the + * {@link java.util.HashMap#get(java.lang.Object)} method returns + * {@code null} if the {@code Map} contains {@code null} or if there + * is no matching key. The {@code Null} placeholder can be used to + * distinguish between these two cases.

+ * + *

Another example is {@code Hashtable}, where {@code null} + * cannot be stored.

+ * + *

This instance is Serializable.

+ */ + public static final Null NULL = new Null(); + + /** + *

{@code ObjectUtils} instances should NOT be constructed in + * standard programming. Instead, the static methods on the class should + * be used, such as {@code ObjectUtils.defaultIfNull("a","b");}.

+ * + *

This constructor is public to permit tools that require a JavaBean + * instance to operate.

+ */ + public ObjectUtils() { + super(); + } + + // Defaulting + //----------------------------------------------------------------------- + /** + *

Returns a default value if the object passed is {@code null}.

+ * + *
+     * ObjectUtils.defaultIfNull(null, null)      = null
+     * ObjectUtils.defaultIfNull(null, "")        = ""
+     * ObjectUtils.defaultIfNull(null, "zz")      = "zz"
+     * ObjectUtils.defaultIfNull("abc", *)        = "abc"
+     * ObjectUtils.defaultIfNull(Boolean.TRUE, *) = Boolean.TRUE
+     * 
+ * + * @param the type of the object + * @param object the {@code Object} to test, may be {@code null} + * @param defaultValue the default value to return, may be {@code null} + * @return {@code object} if it is not {@code null}, defaultValue otherwise + */ + public static T defaultIfNull(final T object, final T defaultValue) { + return object != null ? object : defaultValue; + } + + /** + *

Returns the first value in the array which is not {@code null}. + * If all the values are {@code null} or the array is {@code null} + * or empty then {@code null} is returned.

+ * + *
+     * ObjectUtils.firstNonNull(null, null)      = null
+     * ObjectUtils.firstNonNull(null, "")        = ""
+     * ObjectUtils.firstNonNull(null, null, "")  = ""
+     * ObjectUtils.firstNonNull(null, "zz")      = "zz"
+     * ObjectUtils.firstNonNull("abc", *)        = "abc"
+     * ObjectUtils.firstNonNull(null, "xyz", *)  = "xyz"
+     * ObjectUtils.firstNonNull(Boolean.TRUE, *) = Boolean.TRUE
+     * ObjectUtils.firstNonNull()                = null
+     * 
+ * + * @param the component type of the array + * @param values the values to test, may be {@code null} or empty + * @return the first value from {@code values} which is not {@code null}, + * or {@code null} if there are no non-null values + * @since 3.0 + */ +/** + *

Returns the first value in the array which is not {@code null}. + * If all the values are {@code null} or the array is {@code null} + * or empty then {@code null} is returned.

+ * + *
+ * ObjectUtils.firstNonNull(null, null)      = null
+ * ObjectUtils.firstNonNull(null, "")        = ""
+ * ObjectUtils.firstNonNull(null, null, "")  = ""
+ * ObjectUtils.firstNonNull(null, "zz")      = "zz"
+ * ObjectUtils.firstNonNull("abc", *)        = "abc"
+ * ObjectUtils.firstNonNull(null, "xyz", *)  = "xyz"
+ * ObjectUtils.firstNonNull(Boolean.TRUE, *) = Boolean.TRUE
+ * ObjectUtils.firstNonNull()                = null
+ * 
+ * + * @param + * the component type of the array + * @param values + * the values to test, may be {@code null} or empty + * @return the first value from {@code values} which is not {@code null}, +or {@code null} if there are no non-null values + * @since 3.0 + */ +public static T firstNonNull(final T... values) { + { + for (final T val : /* NPEX_NULL_EXP */ + values) { + if (val != null) { + return val; + } + } + } + return null; +} + + /** + * Checks if any value in the given array is not {@code null}. + * + *

+ * If all the values are {@code null} or the array is {@code null} + * or empty then {@code false} is returned. Otherwise {@code true} is returned. + *

+ * + *
+     * ObjectUtils.anyNotNull(*)                = true
+     * ObjectUtils.anyNotNull(*, null)          = true
+     * ObjectUtils.anyNotNull(null, *)          = true
+     * ObjectUtils.anyNotNull(null, null, *, *) = true
+     * ObjectUtils.anyNotNull(null)             = false
+     * ObjectUtils.anyNotNull(null, null)       = false
+     * 
+ * + * @param values the values to test, may be {@code null} or empty + * @return {@code true} if there is at least one non-null value in the array, + * {@code false} if all values in the array are {@code null}s. + * If the array is {@code null} or empty {@code false} is also returned. + * @since 3.5 + */ + public static boolean anyNotNull(final Object... values) { + return firstNonNull(values) != null; + } + + /** + * Checks if all values in the array are not {@code nulls}. + * + *

+ * If any value is {@code null} or the array is {@code null} then + * {@code false} is returned. If all elements in array are not + * {@code null} or the array is empty (contains no elements) {@code true} + * is returned. + *

+ * + *
+     * ObjectUtils.allNotNull(*)             = true
+     * ObjectUtils.allNotNull(*, *)          = true
+     * ObjectUtils.allNotNull(null)          = false
+     * ObjectUtils.allNotNull(null, null)    = false
+     * ObjectUtils.allNotNull(null, *)       = false
+     * ObjectUtils.allNotNull(*, null)       = false
+     * ObjectUtils.allNotNull(*, *, null, *) = false
+     * 
+ * + * @param values the values to test, may be {@code null} or empty + * @return {@code false} if there is at least one {@code null} value in the array or the array is {@code null}, + * {@code true} if all values in the array are not {@code null}s or array contains no elements. + * @since 3.5 + */ + public static boolean allNotNull(final Object... values) { + if (values == null) { + return false; + } + + for (final Object val : values) { + if (val == null) { + return false; + } + } + + return true; + } + + // Null-safe equals/hashCode + //----------------------------------------------------------------------- + /** + *

Compares two objects for equality, where either one or both + * objects may be {@code null}.

+ * + *
+     * ObjectUtils.equals(null, null)                  = true
+     * ObjectUtils.equals(null, "")                    = false
+     * ObjectUtils.equals("", null)                    = false
+     * ObjectUtils.equals("", "")                      = true
+     * ObjectUtils.equals(Boolean.TRUE, null)          = false
+     * ObjectUtils.equals(Boolean.TRUE, "true")        = false
+     * ObjectUtils.equals(Boolean.TRUE, Boolean.TRUE)  = true
+     * ObjectUtils.equals(Boolean.TRUE, Boolean.FALSE) = false
+     * 
+ * + * @param object1 the first object, may be {@code null} + * @param object2 the second object, may be {@code null} + * @return {@code true} if the values of both objects are the same + * @deprecated this method has been replaced by {@code java.util.Objects.equals(Object, Object)} in Java 7 and will + * be removed from future releases. + */ + @Deprecated + public static boolean equals(final Object object1, final Object object2) { + if (object1 == object2) { + return true; + } + if (object1 == null || object2 == null) { + return false; + } + return object1.equals(object2); + } + + /** + *

Compares two objects for inequality, where either one or both + * objects may be {@code null}.

+ * + *
+     * ObjectUtils.notEqual(null, null)                  = false
+     * ObjectUtils.notEqual(null, "")                    = true
+     * ObjectUtils.notEqual("", null)                    = true
+     * ObjectUtils.notEqual("", "")                      = false
+     * ObjectUtils.notEqual(Boolean.TRUE, null)          = true
+     * ObjectUtils.notEqual(Boolean.TRUE, "true")        = true
+     * ObjectUtils.notEqual(Boolean.TRUE, Boolean.TRUE)  = false
+     * ObjectUtils.notEqual(Boolean.TRUE, Boolean.FALSE) = true
+     * 
+ * + * @param object1 the first object, may be {@code null} + * @param object2 the second object, may be {@code null} + * @return {@code false} if the values of both objects are the same + */ + public static boolean notEqual(final Object object1, final Object object2) { + return ObjectUtils.equals(object1, object2) == false; + } + + /** + *

Gets the hash code of an object returning zero when the + * object is {@code null}.

+ * + *
+     * ObjectUtils.hashCode(null)   = 0
+     * ObjectUtils.hashCode(obj)    = obj.hashCode()
+     * 
+ * + * @param obj the object to obtain the hash code of, may be {@code null} + * @return the hash code of the object, or zero if null + * @since 2.1 + * @deprecated this method has been replaced by {@code java.util.Objects.hashCode(Object)} in Java 7 and will be + * removed in future releases + */ + @Deprecated + public static int hashCode(final Object obj) { + // hashCode(Object) retained for performance, as hash code is often critical + return obj == null ? 0 : obj.hashCode(); + } + + /** + *

Gets the hash code for multiple objects.

+ * + *

This allows a hash code to be rapidly calculated for a number of objects. + * The hash code for a single object is the not same as {@link #hashCode(Object)}. + * The hash code for multiple objects is the same as that calculated by an + * {@code ArrayList} containing the specified objects.

+ * + *
+     * ObjectUtils.hashCodeMulti()                 = 1
+     * ObjectUtils.hashCodeMulti((Object[]) null)  = 1
+     * ObjectUtils.hashCodeMulti(a)                = 31 + a.hashCode()
+     * ObjectUtils.hashCodeMulti(a,b)              = (31 + a.hashCode()) * 31 + b.hashCode()
+     * ObjectUtils.hashCodeMulti(a,b,c)            = ((31 + a.hashCode()) * 31 + b.hashCode()) * 31 + c.hashCode()
+     * 
+ * + * @param objects the objects to obtain the hash code of, may be {@code null} + * @return the hash code of the objects, or zero if null + * @since 3.0 + * @deprecated this method has been replaced by {@code java.util.Objects.hash(Object...)} in Java 7 and will be + * removed in future releases. + */ + @Deprecated + public static int hashCodeMulti(final Object... objects) { + int hash = 1; + if (objects != null) { + for (final Object object : objects) { + final int tmpHash = ObjectUtils.hashCode(object); + hash = hash * 31 + tmpHash; + } + } + return hash; + } + + // Identity ToString + //----------------------------------------------------------------------- + /** + *

Gets the toString that would be produced by {@code Object} + * if a class did not override toString itself. {@code null} + * will return {@code null}.

+ * + *
+     * ObjectUtils.identityToString(null)         = null
+     * ObjectUtils.identityToString("")           = "java.lang.String@1e23"
+     * ObjectUtils.identityToString(Boolean.TRUE) = "java.lang.Boolean@7fa"
+     * 
+ * + * @param object the object to create a toString for, may be + * {@code null} + * @return the default toString text, or {@code null} if + * {@code null} passed in + */ + public static String identityToString(final Object object) { + if (object == null) { + return null; + } + final StringBuilder builder = new StringBuilder(); + identityToString(builder, object); + return builder.toString(); + } + + /** + *

Appends the toString that would be produced by {@code Object} + * if a class did not override toString itself. {@code null} + * will throw a NullPointerException for either of the two parameters.

+ * + *
+     * ObjectUtils.identityToString(appendable, "")            = appendable.append("java.lang.String@1e23"
+     * ObjectUtils.identityToString(appendable, Boolean.TRUE)  = appendable.append("java.lang.Boolean@7fa"
+     * ObjectUtils.identityToString(appendable, Boolean.TRUE)  = appendable.append("java.lang.Boolean@7fa")
+     * 
+ * + * @param appendable the appendable to append to + * @param object the object to create a toString for + * @throws IOException if an I/O error occurs + * @since 3.2 + */ + public static void identityToString(final Appendable appendable, final Object object) throws IOException { + if (object == null) { + throw new NullPointerException("Cannot get the toString of a null identity"); + } + appendable.append(object.getClass().getName()) + .append('@') + .append(Integer.toHexString(System.identityHashCode(object))); + } + + /** + *

Appends the toString that would be produced by {@code Object} + * if a class did not override toString itself. {@code null} + * will throw a NullPointerException for either of the two parameters.

+ * + *
+     * ObjectUtils.identityToString(builder, "")            = builder.append("java.lang.String@1e23"
+     * ObjectUtils.identityToString(builder, Boolean.TRUE)  = builder.append("java.lang.Boolean@7fa"
+     * ObjectUtils.identityToString(builder, Boolean.TRUE)  = builder.append("java.lang.Boolean@7fa")
+     * 
+ * + * @param builder the builder to append to + * @param object the object to create a toString for + * @since 3.2 + */ + public static void identityToString(final StrBuilder builder, final Object object) { + if (object == null) { + throw new NullPointerException("Cannot get the toString of a null identity"); + } + builder.append(object.getClass().getName()) + .append('@') + .append(Integer.toHexString(System.identityHashCode(object))); + } + + /** + *

Appends the toString that would be produced by {@code Object} + * if a class did not override toString itself. {@code null} + * will throw a NullPointerException for either of the two parameters.

+ * + *
+     * ObjectUtils.identityToString(buf, "")            = buf.append("java.lang.String@1e23"
+     * ObjectUtils.identityToString(buf, Boolean.TRUE)  = buf.append("java.lang.Boolean@7fa"
+     * ObjectUtils.identityToString(buf, Boolean.TRUE)  = buf.append("java.lang.Boolean@7fa")
+     * 
+ * + * @param buffer the buffer to append to + * @param object the object to create a toString for + * @since 2.4 + */ + public static void identityToString(final StringBuffer buffer, final Object object) { + if (object == null) { + throw new NullPointerException("Cannot get the toString of a null identity"); + } + buffer.append(object.getClass().getName()) + .append('@') + .append(Integer.toHexString(System.identityHashCode(object))); + } + + /** + *

Appends the toString that would be produced by {@code Object} + * if a class did not override toString itself. {@code null} + * will throw a NullPointerException for either of the two parameters.

+ * + *
+     * ObjectUtils.identityToString(builder, "")            = builder.append("java.lang.String@1e23"
+     * ObjectUtils.identityToString(builder, Boolean.TRUE)  = builder.append("java.lang.Boolean@7fa"
+     * ObjectUtils.identityToString(builder, Boolean.TRUE)  = builder.append("java.lang.Boolean@7fa")
+     * 
+ * + * @param builder the builder to append to + * @param object the object to create a toString for + * @since 3.2 + */ + public static void identityToString(final StringBuilder builder, final Object object) { + if (object == null) { + throw new NullPointerException("Cannot get the toString of a null identity"); + } + builder.append(object.getClass().getName()) + .append('@') + .append(Integer.toHexString(System.identityHashCode(object))); + } + + // ToString + //----------------------------------------------------------------------- + /** + *

Gets the {@code toString} of an {@code Object} returning + * an empty string ("") if {@code null} input.

+ * + *
+     * ObjectUtils.toString(null)         = ""
+     * ObjectUtils.toString("")           = ""
+     * ObjectUtils.toString("bat")        = "bat"
+     * ObjectUtils.toString(Boolean.TRUE) = "true"
+     * 
+ * + * @see StringUtils#defaultString(String) + * @see String#valueOf(Object) + * @param obj the Object to {@code toString}, may be null + * @return the passed in Object's toString, or {@code ""} if {@code null} input + * @since 2.0 + * @deprecated this method has been replaced by {@code java.util.Objects.toString(Object)} in Java 7 and will be + * removed in future releases. Note however that said method will return "null" for null references, while this + * method returns and empty String. To preserve behavior use {@code java.util.Objects.toString(myObject, "")} + */ + @Deprecated + public static String toString(final Object obj) { + return obj == null ? StringUtils.EMPTY : obj.toString(); + } + + /** + *

Gets the {@code toString} of an {@code Object} returning + * a specified text if {@code null} input.

+ * + *
+     * ObjectUtils.toString(null, null)           = null
+     * ObjectUtils.toString(null, "null")         = "null"
+     * ObjectUtils.toString("", "null")           = ""
+     * ObjectUtils.toString("bat", "null")        = "bat"
+     * ObjectUtils.toString(Boolean.TRUE, "null") = "true"
+     * 
+ * + * @see StringUtils#defaultString(String,String) + * @see String#valueOf(Object) + * @param obj the Object to {@code toString}, may be null + * @param nullStr the String to return if {@code null} input, may be null + * @return the passed in Object's toString, or {@code nullStr} if {@code null} input + * @since 2.0 + * @deprecated this method has been replaced by {@code java.util.Objects.toString(Object, String)} in Java 7 and + * will be removed in future releases. + */ + @Deprecated + public static String toString(final Object obj, final String nullStr) { + return obj == null ? nullStr : obj.toString(); + } + + // Comparable + //----------------------------------------------------------------------- + /** + *

Null safe comparison of Comparables.

+ * + * @param type of the values processed by this method + * @param values the set of comparable values, may be null + * @return + *
    + *
  • If any objects are non-null and unequal, the lesser object. + *
  • If all objects are non-null and equal, the first. + *
  • If any of the comparables are null, the lesser of the non-null objects. + *
  • If all the comparables are null, null is returned. + *
+ */ + public static > T min(final T... values) { + T result = null; + if (values != null) { + for (final T value : values) { + if (compare(value, result, true) < 0) { + result = value; + } + } + } + return result; + } + + /** + *

Null safe comparison of Comparables.

+ * + * @param type of the values processed by this method + * @param values the set of comparable values, may be null + * @return + *
    + *
  • If any objects are non-null and unequal, the greater object. + *
  • If all objects are non-null and equal, the first. + *
  • If any of the comparables are null, the greater of the non-null objects. + *
  • If all the comparables are null, null is returned. + *
+ */ + public static > T max(final T... values) { + T result = null; + if (values != null) { + for (final T value : values) { + if (compare(value, result, false) > 0) { + result = value; + } + } + } + return result; + } + + /** + *

Null safe comparison of Comparables. + * {@code null} is assumed to be less than a non-{@code null} value.

+ * + * @param type of the values processed by this method + * @param c1 the first comparable, may be null + * @param c2 the second comparable, may be null + * @return a negative value if c1 < c2, zero if c1 = c2 + * and a positive value if c1 > c2 + */ + public static > int compare(final T c1, final T c2) { + return compare(c1, c2, false); + } + + /** + *

Null safe comparison of Comparables.

+ * + * @param type of the values processed by this method + * @param c1 the first comparable, may be null + * @param c2 the second comparable, may be null + * @param nullGreater if true {@code null} is considered greater + * than a non-{@code null} value or if false {@code null} is + * considered less than a Non-{@code null} value + * @return a negative value if c1 < c2, zero if c1 = c2 + * and a positive value if c1 > c2 + * @see java.util.Comparator#compare(Object, Object) + */ + public static > int compare(final T c1, final T c2, final boolean nullGreater) { + if (c1 == c2) { + return 0; + } else if (c1 == null) { + return nullGreater ? 1 : -1; + } else if (c2 == null) { + return nullGreater ? -1 : 1; + } + return c1.compareTo(c2); + } + + /** + * Find the "best guess" middle value among comparables. If there is an even + * number of total values, the lower of the two middle values will be returned. + * @param type of values processed by this method + * @param items to compare + * @return T at middle position + * @throws NullPointerException if items is {@code null} + * @throws IllegalArgumentException if items is empty or contains {@code null} values + * @since 3.0.1 + */ + public static > T median(final T... items) { + Validate.notEmpty(items); + Validate.noNullElements(items); + final TreeSet sort = new TreeSet(); + Collections.addAll(sort, items); + @SuppressWarnings("unchecked") //we know all items added were T instances + final + T result = (T) sort.toArray()[(sort.size() - 1) / 2]; + return result; + } + + /** + * Find the "best guess" middle value among comparables. If there is an even + * number of total values, the lower of the two middle values will be returned. + * @param type of values processed by this method + * @param comparator to use for comparisons + * @param items to compare + * @return T at middle position + * @throws NullPointerException if items or comparator is {@code null} + * @throws IllegalArgumentException if items is empty or contains {@code null} values + * @since 3.0.1 + */ + public static T median(final Comparator comparator, final T... items) { + Validate.notEmpty(items, "null/empty items"); + Validate.noNullElements(items); + Validate.notNull(comparator, "null comparator"); + final TreeSet sort = new TreeSet(comparator); + Collections.addAll(sort, items); + @SuppressWarnings("unchecked") //we know all items added were T instances + final + T result = (T) sort.toArray()[(sort.size() - 1) / 2]; + return result; + } + + // Mode + //----------------------------------------------------------------------- + /** + * Find the most frequently occurring item. + * + * @param type of values processed by this method + * @param items to check + * @return most populous T, {@code null} if non-unique or no items supplied + * @since 3.0.1 + */ + public static T mode(final T... items) { + if (ArrayUtils.isNotEmpty(items)) { + final HashMap occurrences = new HashMap(items.length); + for (final T t : items) { + final MutableInt count = occurrences.get(t); + if (count == null) { + occurrences.put(t, new MutableInt(1)); + } else { + count.increment(); + } + } + T result = null; + int max = 0; + for (final Map.Entry e : occurrences.entrySet()) { + final int cmp = e.getValue().intValue(); + if (cmp == max) { + result = null; + } else if (cmp > max) { + max = cmp; + result = e.getKey(); + } + } + return result; + } + return null; + } + + // cloning + //----------------------------------------------------------------------- + /** + *

Clone an object.

+ * + * @param the type of the object + * @param obj the object to clone, null returns null + * @return the clone if the object implements {@link Cloneable} otherwise {@code null} + * @throws CloneFailedException if the object is cloneable and the clone operation fails + * @since 3.0 + */ + public static T clone(final T obj) { + if (obj instanceof Cloneable) { + final Object result; + if (obj.getClass().isArray()) { + final Class componentType = obj.getClass().getComponentType(); + if (!componentType.isPrimitive()) { + result = ((Object[]) obj).clone(); + } else { + int length = Array.getLength(obj); + result = Array.newInstance(componentType, length); + while (length-- > 0) { + Array.set(result, length, Array.get(obj, length)); + } + } + } else { + try { + final Method clone = obj.getClass().getMethod("clone"); + result = clone.invoke(obj); + } catch (final NoSuchMethodException e) { + throw new CloneFailedException("Cloneable type " + + obj.getClass().getName() + + " has no clone method", e); + } catch (final IllegalAccessException e) { + throw new CloneFailedException("Cannot clone Cloneable type " + + obj.getClass().getName(), e); + } catch (final InvocationTargetException e) { + throw new CloneFailedException("Exception cloning Cloneable type " + + obj.getClass().getName(), e.getCause()); + } + } + @SuppressWarnings("unchecked") // OK because input is of type T + final T checked = (T) result; + return checked; + } + + return null; + } + + /** + *

Clone an object if possible.

+ * + *

This method is similar to {@link #clone(Object)}, but will return the provided + * instance as the return value instead of {@code null} if the instance + * is not cloneable. This is more convenient if the caller uses different + * implementations (e.g. of a service) and some of the implementations do not allow concurrent + * processing or have state. In such cases the implementation can simply provide a proper + * clone implementation and the caller's code does not have to change.

+ * + * @param the type of the object + * @param obj the object to clone, null returns null + * @return the clone if the object implements {@link Cloneable} otherwise the object itself + * @throws CloneFailedException if the object is cloneable and the clone operation fails + * @since 3.0 + */ + public static T cloneIfPossible(final T obj) { + final T clone = clone(obj); + return clone == null ? obj : clone; + } + + // Null + //----------------------------------------------------------------------- + /** + *

Class used as a null placeholder where {@code null} + * has another meaning.

+ * + *

For example, in a {@code HashMap} the + * {@link java.util.HashMap#get(java.lang.Object)} method returns + * {@code null} if the {@code Map} contains {@code null} or if there is + * no matching key. The {@code Null} placeholder can be used to distinguish + * between these two cases.

+ * + *

Another example is {@code Hashtable}, where {@code null} + * cannot be stored.

+ */ + public static class Null implements Serializable { + /** + * Required for serialization support. Declare serialization compatibility with Commons Lang 1.0 + * + * @see java.io.Serializable + */ + private static final long serialVersionUID = 7092611880189329093L; + + /** + * Restricted constructor - singleton. + */ + Null() { + super(); + } + + /** + *

Ensure singleton.

+ * + * @return the singleton value + */ + private Object readResolve() { + return ObjectUtils.NULL; + } + } + + + // Constants (LANG-816): + /* + These methods ensure constants are not inlined by javac. + For example, typically a developer might declare a constant like so: + + public final static int MAGIC_NUMBER = 5; + + Should a different jar file refer to this, and the MAGIC_NUMBER + is changed a later date (e.g., MAGIC_NUMBER = 6), the different jar + file will need to recompile itself. This is because javac + typically inlines the primitive or String constant directly into + the bytecode, and removes the reference to the MAGIC_NUMBER field. + + To help the other jar (so that it does not need to recompile + when constants are changed) the original developer can declare + their constant using one of the CONST() utility methods, instead: + + public final static int MAGIC_NUMBER = CONST(5); + */ + + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static boolean MAGIC_FLAG = ObjectUtils.CONST(true);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the boolean value to return + * @return the boolean v, unchanged + * @since 3.2 + */ + public static boolean CONST(final boolean v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static byte MAGIC_BYTE = ObjectUtils.CONST((byte) 127);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the byte value to return + * @return the byte v, unchanged + * @since 3.2 + */ + public static byte CONST(final byte v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static byte MAGIC_BYTE = ObjectUtils.CONST_BYTE(127);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the byte literal (as an int) value to return + * @throws IllegalArgumentException if the value passed to v + * is larger than a byte, that is, smaller than -128 or + * larger than 127. + * @return the byte v, unchanged + * @since 3.2 + */ + public static byte CONST_BYTE(final int v) throws IllegalArgumentException { + if (v < Byte.MIN_VALUE || v > Byte.MAX_VALUE) { + throw new IllegalArgumentException("Supplied value must be a valid byte literal between -128 and 127: [" + v + "]"); + } + return (byte) v; + } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static char MAGIC_CHAR = ObjectUtils.CONST('a');
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the char value to return + * @return the char v, unchanged + * @since 3.2 + */ + public static char CONST(final char v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static short MAGIC_SHORT = ObjectUtils.CONST((short) 123);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the short value to return + * @return the short v, unchanged + * @since 3.2 + */ + public static short CONST(final short v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static short MAGIC_SHORT = ObjectUtils.CONST_SHORT(127);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the short literal (as an int) value to return + * @throws IllegalArgumentException if the value passed to v + * is larger than a short, that is, smaller than -32768 or + * larger than 32767. + * @return the byte v, unchanged + * @since 3.2 + */ + public static short CONST_SHORT(final int v) throws IllegalArgumentException { + if (v < Short.MIN_VALUE || v > Short.MAX_VALUE) { + throw new IllegalArgumentException("Supplied value must be a valid byte literal between -32768 and 32767: [" + v + "]"); + } + return (short) v; + } + + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static int MAGIC_INT = ObjectUtils.CONST(123);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the int value to return + * @return the int v, unchanged + * @since 3.2 + */ + public static int CONST(final int v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static long MAGIC_LONG = ObjectUtils.CONST(123L);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the long value to return + * @return the long v, unchanged + * @since 3.2 + */ + public static long CONST(final long v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static float MAGIC_FLOAT = ObjectUtils.CONST(1.0f);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the float value to return + * @return the float v, unchanged + * @since 3.2 + */ + public static float CONST(final float v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static double MAGIC_DOUBLE = ObjectUtils.CONST(1.0);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the double value to return + * @return the double v, unchanged + * @since 3.2 + */ + public static double CONST(final double v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static String MAGIC_STRING = ObjectUtils.CONST("abc");
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param the Object type + * @param v the genericized Object value to return (typically a String). + * @return the genericized Object v, unchanged (typically a String). + * @since 3.2 + */ + public static T CONST(final T v) { return v; } + +} diff --git a/Java/commons-lang-ObjectUtils_121/metadata.json b/Java/commons-lang-ObjectUtils_121/metadata.json new file mode 100644 index 000000000..188fd11ec --- /dev/null +++ b/Java/commons-lang-ObjectUtils_121/metadata.json @@ -0,0 +1,21 @@ +{ + "language": "java", + "id": "commons-lang-ObjectUtils_121", + "buggyPath": ".", + "referencePath": null, + "buildCommand": "mvn package -V -B -Denforcer.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true -Drat.skip=true -Dlicense.skip=true -Dfindbugs.skip=true -Dgpg.skip=true -Dskip.npm=true -Dskip.gulp=true -Dskip.bower=true -Drat.numUnapprovedLicenses=100 -DskipTests=true -DskipITs=true -Dtest=None -DfailIfNoTests=false", + "testCommand": "mvn test -V -B -Denforcer.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true -Drat.skip=true -Dlicense.skip=true -Dfindbugs.skip=true -Dgpg.skip=true -Dskip.npm=true -Dskip.gulp=true -Dskip.bower=true -Drat.numUnapprovedLicenses=100", + "categories": [ + "safety", + "npe" + ], + "npe": { + "filepath": "src/main/java/org/apache/commons/lang3/ObjectUtils.java", + "line": 147, + "npe_method": "firstNonNull", + "deref_field": "values", + "npe_class": "ObjectUtils", + "repo": "commons-lang", + "bug_id": "ObjectUtils_121" + } +} diff --git a/Java/commons-lang-ObjectUtils_121/npe.json b/Java/commons-lang-ObjectUtils_121/npe.json new file mode 100644 index 000000000..8e6c6ee6e --- /dev/null +++ b/Java/commons-lang-ObjectUtils_121/npe.json @@ -0,0 +1,7 @@ +{ + "filepath": "src/main/java/org/apache/commons/lang3/ObjectUtils.java", + "line": 147, + "npe_method": "firstNonNull", + "deref_field": "values", + "npe_class": "ObjectUtils" +} \ No newline at end of file diff --git a/Java/commons-lang-ObjectUtils_123/Dockerfile b/Java/commons-lang-ObjectUtils_123/Dockerfile new file mode 100644 index 000000000..7b7fbe349 --- /dev/null +++ b/Java/commons-lang-ObjectUtils_123/Dockerfile @@ -0,0 +1,18 @@ +FROM ghcr.io/kupl/starlab-benchmarks/java-base:commons-lang + +ENV TZ=Asia/Seoul + +COPY ./metadata.json . +COPY ./npe.json . +COPY ./buggy.java /tmp/buggy.java +RUN export BUGGY_PATH=$(cat metadata.json | jq -r ".npe.filepath") \ + && export BUGGY_LINE=$(cat metadata.json | jq -r ".npe.line") \ + && export BUGGY_MTHD=$(cat metadata.json | jq -r ".npe.npe_method") \ + && mv /tmp/buggy.java $BUGGY_PATH \ + && echo "[{\"filepath\": \"$BUGGY_PATH\", \"line\": $BUGGY_LINE, \"method_name\": \"$BUGGY_MTHD\"}]" | jq . > traces.json + +RUN git init . && git add -A + +RUN $(cat metadata.json | jq -r ".buildCommand") + +RUN $(cat metadata.json | jq -r ".testCommand"); if [ $? -eq 0 ]; then exit 1; fi diff --git a/Java/commons-lang-ObjectUtils_123/buggy.java b/Java/commons-lang-ObjectUtils_123/buggy.java new file mode 100644 index 000000000..7237a475f --- /dev/null +++ b/Java/commons-lang-ObjectUtils_123/buggy.java @@ -0,0 +1,1041 @@ +/* + * 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.Serializable; +import java.lang.reflect.Array; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.Map; +import java.util.TreeSet; + +import org.apache.commons.lang3.exception.CloneFailedException; +import org.apache.commons.lang3.mutable.MutableInt; +import org.apache.commons.lang3.text.StrBuilder; + +/** + *

Operations on {@code Object}.

+ * + *

This class tries to handle {@code null} input gracefully. + * An exception will generally not be thrown for a {@code null} input. + * Each method documents its behaviour in more detail.

+ * + *

#ThreadSafe#

+ * @since 1.0 + */ +//@Immutable +public class ObjectUtils { + + /** + *

Singleton used as a {@code null} placeholder where + * {@code null} has another meaning.

+ * + *

For example, in a {@code HashMap} the + * {@link java.util.HashMap#get(java.lang.Object)} method returns + * {@code null} if the {@code Map} contains {@code null} or if there + * is no matching key. The {@code Null} placeholder can be used to + * distinguish between these two cases.

+ * + *

Another example is {@code Hashtable}, where {@code null} + * cannot be stored.

+ * + *

This instance is Serializable.

+ */ + public static final Null NULL = new Null(); + + /** + *

{@code ObjectUtils} instances should NOT be constructed in + * standard programming. Instead, the static methods on the class should + * be used, such as {@code ObjectUtils.defaultIfNull("a","b");}.

+ * + *

This constructor is public to permit tools that require a JavaBean + * instance to operate.

+ */ + public ObjectUtils() { + super(); + } + + // Defaulting + //----------------------------------------------------------------------- + /** + *

Returns a default value if the object passed is {@code null}.

+ * + *
+     * ObjectUtils.defaultIfNull(null, null)      = null
+     * ObjectUtils.defaultIfNull(null, "")        = ""
+     * ObjectUtils.defaultIfNull(null, "zz")      = "zz"
+     * ObjectUtils.defaultIfNull("abc", *)        = "abc"
+     * ObjectUtils.defaultIfNull(Boolean.TRUE, *) = Boolean.TRUE
+     * 
+ * + * @param the type of the object + * @param object the {@code Object} to test, may be {@code null} + * @param defaultValue the default value to return, may be {@code null} + * @return {@code object} if it is not {@code null}, defaultValue otherwise + */ + public static T defaultIfNull(final T object, final T defaultValue) { + return object != null ? object : defaultValue; + } + + /** + *

Returns the first value in the array which is not {@code null}. + * If all the values are {@code null} or the array is {@code null} + * or empty then {@code null} is returned.

+ * + *
+     * ObjectUtils.firstNonNull(null, null)      = null
+     * ObjectUtils.firstNonNull(null, "")        = ""
+     * ObjectUtils.firstNonNull(null, null, "")  = ""
+     * ObjectUtils.firstNonNull(null, "zz")      = "zz"
+     * ObjectUtils.firstNonNull("abc", *)        = "abc"
+     * ObjectUtils.firstNonNull(null, "xyz", *)  = "xyz"
+     * ObjectUtils.firstNonNull(Boolean.TRUE, *) = Boolean.TRUE
+     * ObjectUtils.firstNonNull()                = null
+     * 
+ * + * @param the component type of the array + * @param values the values to test, may be {@code null} or empty + * @return the first value from {@code values} which is not {@code null}, + * or {@code null} if there are no non-null values + * @since 3.0 + */ +/** + *

Returns the first value in the array which is not {@code null}. + * If all the values are {@code null} or the array is {@code null} + * or empty then {@code null} is returned.

+ * + *
+ * ObjectUtils.firstNonNull(null, null)      = null
+ * ObjectUtils.firstNonNull(null, "")        = ""
+ * ObjectUtils.firstNonNull(null, null, "")  = ""
+ * ObjectUtils.firstNonNull(null, "zz")      = "zz"
+ * ObjectUtils.firstNonNull("abc", *)        = "abc"
+ * ObjectUtils.firstNonNull(null, "xyz", *)  = "xyz"
+ * ObjectUtils.firstNonNull(Boolean.TRUE, *) = Boolean.TRUE
+ * ObjectUtils.firstNonNull()                = null
+ * 
+ * + * @param + * the component type of the array + * @param values + * the values to test, may be {@code null} or empty + * @return the first value from {@code values} which is not {@code null}, +or {@code null} if there are no non-null values + * @since 3.0 + */ +public static T firstNonNull(final T... values) { + { + for (final T val : values) { + { + return /* NPEX_NULL_EXP */ + val; + } + } + } + return null; +} + + /** + * Checks if any value in the given array is not {@code null}. + * + *

+ * If all the values are {@code null} or the array is {@code null} + * or empty then {@code false} is returned. Otherwise {@code true} is returned. + *

+ * + *
+     * ObjectUtils.anyNotNull(*)                = true
+     * ObjectUtils.anyNotNull(*, null)          = true
+     * ObjectUtils.anyNotNull(null, *)          = true
+     * ObjectUtils.anyNotNull(null, null, *, *) = true
+     * ObjectUtils.anyNotNull(null)             = false
+     * ObjectUtils.anyNotNull(null, null)       = false
+     * 
+ * + * @param values the values to test, may be {@code null} or empty + * @return {@code true} if there is at least one non-null value in the array, + * {@code false} if all values in the array are {@code null}s. + * If the array is {@code null} or empty {@code false} is also returned. + * @since 3.5 + */ + public static boolean anyNotNull(final Object... values) { + return firstNonNull(values) != null; + } + + /** + * Checks if all values in the array are not {@code nulls}. + * + *

+ * If any value is {@code null} or the array is {@code null} then + * {@code false} is returned. If all elements in array are not + * {@code null} or the array is empty (contains no elements) {@code true} + * is returned. + *

+ * + *
+     * ObjectUtils.allNotNull(*)             = true
+     * ObjectUtils.allNotNull(*, *)          = true
+     * ObjectUtils.allNotNull(null)          = false
+     * ObjectUtils.allNotNull(null, null)    = false
+     * ObjectUtils.allNotNull(null, *)       = false
+     * ObjectUtils.allNotNull(*, null)       = false
+     * ObjectUtils.allNotNull(*, *, null, *) = false
+     * 
+ * + * @param values the values to test, may be {@code null} or empty + * @return {@code false} if there is at least one {@code null} value in the array or the array is {@code null}, + * {@code true} if all values in the array are not {@code null}s or array contains no elements. + * @since 3.5 + */ + public static boolean allNotNull(final Object... values) { + if (values == null) { + return false; + } + + for (final Object val : values) { + if (val == null) { + return false; + } + } + + return true; + } + + // Null-safe equals/hashCode + //----------------------------------------------------------------------- + /** + *

Compares two objects for equality, where either one or both + * objects may be {@code null}.

+ * + *
+     * ObjectUtils.equals(null, null)                  = true
+     * ObjectUtils.equals(null, "")                    = false
+     * ObjectUtils.equals("", null)                    = false
+     * ObjectUtils.equals("", "")                      = true
+     * ObjectUtils.equals(Boolean.TRUE, null)          = false
+     * ObjectUtils.equals(Boolean.TRUE, "true")        = false
+     * ObjectUtils.equals(Boolean.TRUE, Boolean.TRUE)  = true
+     * ObjectUtils.equals(Boolean.TRUE, Boolean.FALSE) = false
+     * 
+ * + * @param object1 the first object, may be {@code null} + * @param object2 the second object, may be {@code null} + * @return {@code true} if the values of both objects are the same + * @deprecated this method has been replaced by {@code java.util.Objects.equals(Object, Object)} in Java 7 and will + * be removed from future releases. + */ + @Deprecated + public static boolean equals(final Object object1, final Object object2) { + if (object1 == object2) { + return true; + } + if (object1 == null || object2 == null) { + return false; + } + return object1.equals(object2); + } + + /** + *

Compares two objects for inequality, where either one or both + * objects may be {@code null}.

+ * + *
+     * ObjectUtils.notEqual(null, null)                  = false
+     * ObjectUtils.notEqual(null, "")                    = true
+     * ObjectUtils.notEqual("", null)                    = true
+     * ObjectUtils.notEqual("", "")                      = false
+     * ObjectUtils.notEqual(Boolean.TRUE, null)          = true
+     * ObjectUtils.notEqual(Boolean.TRUE, "true")        = true
+     * ObjectUtils.notEqual(Boolean.TRUE, Boolean.TRUE)  = false
+     * ObjectUtils.notEqual(Boolean.TRUE, Boolean.FALSE) = true
+     * 
+ * + * @param object1 the first object, may be {@code null} + * @param object2 the second object, may be {@code null} + * @return {@code false} if the values of both objects are the same + */ + public static boolean notEqual(final Object object1, final Object object2) { + return ObjectUtils.equals(object1, object2) == false; + } + + /** + *

Gets the hash code of an object returning zero when the + * object is {@code null}.

+ * + *
+     * ObjectUtils.hashCode(null)   = 0
+     * ObjectUtils.hashCode(obj)    = obj.hashCode()
+     * 
+ * + * @param obj the object to obtain the hash code of, may be {@code null} + * @return the hash code of the object, or zero if null + * @since 2.1 + * @deprecated this method has been replaced by {@code java.util.Objects.hashCode(Object)} in Java 7 and will be + * removed in future releases + */ + @Deprecated + public static int hashCode(final Object obj) { + // hashCode(Object) retained for performance, as hash code is often critical + return obj == null ? 0 : obj.hashCode(); + } + + /** + *

Gets the hash code for multiple objects.

+ * + *

This allows a hash code to be rapidly calculated for a number of objects. + * The hash code for a single object is the not same as {@link #hashCode(Object)}. + * The hash code for multiple objects is the same as that calculated by an + * {@code ArrayList} containing the specified objects.

+ * + *
+     * ObjectUtils.hashCodeMulti()                 = 1
+     * ObjectUtils.hashCodeMulti((Object[]) null)  = 1
+     * ObjectUtils.hashCodeMulti(a)                = 31 + a.hashCode()
+     * ObjectUtils.hashCodeMulti(a,b)              = (31 + a.hashCode()) * 31 + b.hashCode()
+     * ObjectUtils.hashCodeMulti(a,b,c)            = ((31 + a.hashCode()) * 31 + b.hashCode()) * 31 + c.hashCode()
+     * 
+ * + * @param objects the objects to obtain the hash code of, may be {@code null} + * @return the hash code of the objects, or zero if null + * @since 3.0 + * @deprecated this method has been replaced by {@code java.util.Objects.hash(Object...)} in Java 7 and will be + * removed in future releases. + */ + @Deprecated + public static int hashCodeMulti(final Object... objects) { + int hash = 1; + if (objects != null) { + for (final Object object : objects) { + final int tmpHash = ObjectUtils.hashCode(object); + hash = hash * 31 + tmpHash; + } + } + return hash; + } + + // Identity ToString + //----------------------------------------------------------------------- + /** + *

Gets the toString that would be produced by {@code Object} + * if a class did not override toString itself. {@code null} + * will return {@code null}.

+ * + *
+     * ObjectUtils.identityToString(null)         = null
+     * ObjectUtils.identityToString("")           = "java.lang.String@1e23"
+     * ObjectUtils.identityToString(Boolean.TRUE) = "java.lang.Boolean@7fa"
+     * 
+ * + * @param object the object to create a toString for, may be + * {@code null} + * @return the default toString text, or {@code null} if + * {@code null} passed in + */ + public static String identityToString(final Object object) { + if (object == null) { + return null; + } + final StringBuilder builder = new StringBuilder(); + identityToString(builder, object); + return builder.toString(); + } + + /** + *

Appends the toString that would be produced by {@code Object} + * if a class did not override toString itself. {@code null} + * will throw a NullPointerException for either of the two parameters.

+ * + *
+     * ObjectUtils.identityToString(appendable, "")            = appendable.append("java.lang.String@1e23"
+     * ObjectUtils.identityToString(appendable, Boolean.TRUE)  = appendable.append("java.lang.Boolean@7fa"
+     * ObjectUtils.identityToString(appendable, Boolean.TRUE)  = appendable.append("java.lang.Boolean@7fa")
+     * 
+ * + * @param appendable the appendable to append to + * @param object the object to create a toString for + * @throws IOException if an I/O error occurs + * @since 3.2 + */ + public static void identityToString(final Appendable appendable, final Object object) throws IOException { + if (object == null) { + throw new NullPointerException("Cannot get the toString of a null identity"); + } + appendable.append(object.getClass().getName()) + .append('@') + .append(Integer.toHexString(System.identityHashCode(object))); + } + + /** + *

Appends the toString that would be produced by {@code Object} + * if a class did not override toString itself. {@code null} + * will throw a NullPointerException for either of the two parameters.

+ * + *
+     * ObjectUtils.identityToString(builder, "")            = builder.append("java.lang.String@1e23"
+     * ObjectUtils.identityToString(builder, Boolean.TRUE)  = builder.append("java.lang.Boolean@7fa"
+     * ObjectUtils.identityToString(builder, Boolean.TRUE)  = builder.append("java.lang.Boolean@7fa")
+     * 
+ * + * @param builder the builder to append to + * @param object the object to create a toString for + * @since 3.2 + */ + public static void identityToString(final StrBuilder builder, final Object object) { + if (object == null) { + throw new NullPointerException("Cannot get the toString of a null identity"); + } + builder.append(object.getClass().getName()) + .append('@') + .append(Integer.toHexString(System.identityHashCode(object))); + } + + /** + *

Appends the toString that would be produced by {@code Object} + * if a class did not override toString itself. {@code null} + * will throw a NullPointerException for either of the two parameters.

+ * + *
+     * ObjectUtils.identityToString(buf, "")            = buf.append("java.lang.String@1e23"
+     * ObjectUtils.identityToString(buf, Boolean.TRUE)  = buf.append("java.lang.Boolean@7fa"
+     * ObjectUtils.identityToString(buf, Boolean.TRUE)  = buf.append("java.lang.Boolean@7fa")
+     * 
+ * + * @param buffer the buffer to append to + * @param object the object to create a toString for + * @since 2.4 + */ + public static void identityToString(final StringBuffer buffer, final Object object) { + if (object == null) { + throw new NullPointerException("Cannot get the toString of a null identity"); + } + buffer.append(object.getClass().getName()) + .append('@') + .append(Integer.toHexString(System.identityHashCode(object))); + } + + /** + *

Appends the toString that would be produced by {@code Object} + * if a class did not override toString itself. {@code null} + * will throw a NullPointerException for either of the two parameters.

+ * + *
+     * ObjectUtils.identityToString(builder, "")            = builder.append("java.lang.String@1e23"
+     * ObjectUtils.identityToString(builder, Boolean.TRUE)  = builder.append("java.lang.Boolean@7fa"
+     * ObjectUtils.identityToString(builder, Boolean.TRUE)  = builder.append("java.lang.Boolean@7fa")
+     * 
+ * + * @param builder the builder to append to + * @param object the object to create a toString for + * @since 3.2 + */ + public static void identityToString(final StringBuilder builder, final Object object) { + if (object == null) { + throw new NullPointerException("Cannot get the toString of a null identity"); + } + builder.append(object.getClass().getName()) + .append('@') + .append(Integer.toHexString(System.identityHashCode(object))); + } + + // ToString + //----------------------------------------------------------------------- + /** + *

Gets the {@code toString} of an {@code Object} returning + * an empty string ("") if {@code null} input.

+ * + *
+     * ObjectUtils.toString(null)         = ""
+     * ObjectUtils.toString("")           = ""
+     * ObjectUtils.toString("bat")        = "bat"
+     * ObjectUtils.toString(Boolean.TRUE) = "true"
+     * 
+ * + * @see StringUtils#defaultString(String) + * @see String#valueOf(Object) + * @param obj the Object to {@code toString}, may be null + * @return the passed in Object's toString, or {@code ""} if {@code null} input + * @since 2.0 + * @deprecated this method has been replaced by {@code java.util.Objects.toString(Object)} in Java 7 and will be + * removed in future releases. Note however that said method will return "null" for null references, while this + * method returns and empty String. To preserve behavior use {@code java.util.Objects.toString(myObject, "")} + */ + @Deprecated + public static String toString(final Object obj) { + return obj == null ? StringUtils.EMPTY : obj.toString(); + } + + /** + *

Gets the {@code toString} of an {@code Object} returning + * a specified text if {@code null} input.

+ * + *
+     * ObjectUtils.toString(null, null)           = null
+     * ObjectUtils.toString(null, "null")         = "null"
+     * ObjectUtils.toString("", "null")           = ""
+     * ObjectUtils.toString("bat", "null")        = "bat"
+     * ObjectUtils.toString(Boolean.TRUE, "null") = "true"
+     * 
+ * + * @see StringUtils#defaultString(String,String) + * @see String#valueOf(Object) + * @param obj the Object to {@code toString}, may be null + * @param nullStr the String to return if {@code null} input, may be null + * @return the passed in Object's toString, or {@code nullStr} if {@code null} input + * @since 2.0 + * @deprecated this method has been replaced by {@code java.util.Objects.toString(Object, String)} in Java 7 and + * will be removed in future releases. + */ + @Deprecated + public static String toString(final Object obj, final String nullStr) { + return obj == null ? nullStr : obj.toString(); + } + + // Comparable + //----------------------------------------------------------------------- + /** + *

Null safe comparison of Comparables.

+ * + * @param type of the values processed by this method + * @param values the set of comparable values, may be null + * @return + *
    + *
  • If any objects are non-null and unequal, the lesser object. + *
  • If all objects are non-null and equal, the first. + *
  • If any of the comparables are null, the lesser of the non-null objects. + *
  • If all the comparables are null, null is returned. + *
+ */ + public static > T min(final T... values) { + T result = null; + if (values != null) { + for (final T value : values) { + if (compare(value, result, true) < 0) { + result = value; + } + } + } + return result; + } + + /** + *

Null safe comparison of Comparables.

+ * + * @param type of the values processed by this method + * @param values the set of comparable values, may be null + * @return + *
    + *
  • If any objects are non-null and unequal, the greater object. + *
  • If all objects are non-null and equal, the first. + *
  • If any of the comparables are null, the greater of the non-null objects. + *
  • If all the comparables are null, null is returned. + *
+ */ + public static > T max(final T... values) { + T result = null; + if (values != null) { + for (final T value : values) { + if (compare(value, result, false) > 0) { + result = value; + } + } + } + return result; + } + + /** + *

Null safe comparison of Comparables. + * {@code null} is assumed to be less than a non-{@code null} value.

+ * + * @param type of the values processed by this method + * @param c1 the first comparable, may be null + * @param c2 the second comparable, may be null + * @return a negative value if c1 < c2, zero if c1 = c2 + * and a positive value if c1 > c2 + */ + public static > int compare(final T c1, final T c2) { + return compare(c1, c2, false); + } + + /** + *

Null safe comparison of Comparables.

+ * + * @param type of the values processed by this method + * @param c1 the first comparable, may be null + * @param c2 the second comparable, may be null + * @param nullGreater if true {@code null} is considered greater + * than a non-{@code null} value or if false {@code null} is + * considered less than a Non-{@code null} value + * @return a negative value if c1 < c2, zero if c1 = c2 + * and a positive value if c1 > c2 + * @see java.util.Comparator#compare(Object, Object) + */ + public static > int compare(final T c1, final T c2, final boolean nullGreater) { + if (c1 == c2) { + return 0; + } else if (c1 == null) { + return nullGreater ? 1 : -1; + } else if (c2 == null) { + return nullGreater ? -1 : 1; + } + return c1.compareTo(c2); + } + + /** + * Find the "best guess" middle value among comparables. If there is an even + * number of total values, the lower of the two middle values will be returned. + * @param type of values processed by this method + * @param items to compare + * @return T at middle position + * @throws NullPointerException if items is {@code null} + * @throws IllegalArgumentException if items is empty or contains {@code null} values + * @since 3.0.1 + */ + public static > T median(final T... items) { + Validate.notEmpty(items); + Validate.noNullElements(items); + final TreeSet sort = new TreeSet(); + Collections.addAll(sort, items); + @SuppressWarnings("unchecked") //we know all items added were T instances + final + T result = (T) sort.toArray()[(sort.size() - 1) / 2]; + return result; + } + + /** + * Find the "best guess" middle value among comparables. If there is an even + * number of total values, the lower of the two middle values will be returned. + * @param type of values processed by this method + * @param comparator to use for comparisons + * @param items to compare + * @return T at middle position + * @throws NullPointerException if items or comparator is {@code null} + * @throws IllegalArgumentException if items is empty or contains {@code null} values + * @since 3.0.1 + */ + public static T median(final Comparator comparator, final T... items) { + Validate.notEmpty(items, "null/empty items"); + Validate.noNullElements(items); + Validate.notNull(comparator, "null comparator"); + final TreeSet sort = new TreeSet(comparator); + Collections.addAll(sort, items); + @SuppressWarnings("unchecked") //we know all items added were T instances + final + T result = (T) sort.toArray()[(sort.size() - 1) / 2]; + return result; + } + + // Mode + //----------------------------------------------------------------------- + /** + * Find the most frequently occurring item. + * + * @param type of values processed by this method + * @param items to check + * @return most populous T, {@code null} if non-unique or no items supplied + * @since 3.0.1 + */ + public static T mode(final T... items) { + if (ArrayUtils.isNotEmpty(items)) { + final HashMap occurrences = new HashMap(items.length); + for (final T t : items) { + final MutableInt count = occurrences.get(t); + if (count == null) { + occurrences.put(t, new MutableInt(1)); + } else { + count.increment(); + } + } + T result = null; + int max = 0; + for (final Map.Entry e : occurrences.entrySet()) { + final int cmp = e.getValue().intValue(); + if (cmp == max) { + result = null; + } else if (cmp > max) { + max = cmp; + result = e.getKey(); + } + } + return result; + } + return null; + } + + // cloning + //----------------------------------------------------------------------- + /** + *

Clone an object.

+ * + * @param the type of the object + * @param obj the object to clone, null returns null + * @return the clone if the object implements {@link Cloneable} otherwise {@code null} + * @throws CloneFailedException if the object is cloneable and the clone operation fails + * @since 3.0 + */ + public static T clone(final T obj) { + if (obj instanceof Cloneable) { + final Object result; + if (obj.getClass().isArray()) { + final Class componentType = obj.getClass().getComponentType(); + if (!componentType.isPrimitive()) { + result = ((Object[]) obj).clone(); + } else { + int length = Array.getLength(obj); + result = Array.newInstance(componentType, length); + while (length-- > 0) { + Array.set(result, length, Array.get(obj, length)); + } + } + } else { + try { + final Method clone = obj.getClass().getMethod("clone"); + result = clone.invoke(obj); + } catch (final NoSuchMethodException e) { + throw new CloneFailedException("Cloneable type " + + obj.getClass().getName() + + " has no clone method", e); + } catch (final IllegalAccessException e) { + throw new CloneFailedException("Cannot clone Cloneable type " + + obj.getClass().getName(), e); + } catch (final InvocationTargetException e) { + throw new CloneFailedException("Exception cloning Cloneable type " + + obj.getClass().getName(), e.getCause()); + } + } + @SuppressWarnings("unchecked") // OK because input is of type T + final T checked = (T) result; + return checked; + } + + return null; + } + + /** + *

Clone an object if possible.

+ * + *

This method is similar to {@link #clone(Object)}, but will return the provided + * instance as the return value instead of {@code null} if the instance + * is not cloneable. This is more convenient if the caller uses different + * implementations (e.g. of a service) and some of the implementations do not allow concurrent + * processing or have state. In such cases the implementation can simply provide a proper + * clone implementation and the caller's code does not have to change.

+ * + * @param the type of the object + * @param obj the object to clone, null returns null + * @return the clone if the object implements {@link Cloneable} otherwise the object itself + * @throws CloneFailedException if the object is cloneable and the clone operation fails + * @since 3.0 + */ + public static T cloneIfPossible(final T obj) { + final T clone = clone(obj); + return clone == null ? obj : clone; + } + + // Null + //----------------------------------------------------------------------- + /** + *

Class used as a null placeholder where {@code null} + * has another meaning.

+ * + *

For example, in a {@code HashMap} the + * {@link java.util.HashMap#get(java.lang.Object)} method returns + * {@code null} if the {@code Map} contains {@code null} or if there is + * no matching key. The {@code Null} placeholder can be used to distinguish + * between these two cases.

+ * + *

Another example is {@code Hashtable}, where {@code null} + * cannot be stored.

+ */ + public static class Null implements Serializable { + /** + * Required for serialization support. Declare serialization compatibility with Commons Lang 1.0 + * + * @see java.io.Serializable + */ + private static final long serialVersionUID = 7092611880189329093L; + + /** + * Restricted constructor - singleton. + */ + Null() { + super(); + } + + /** + *

Ensure singleton.

+ * + * @return the singleton value + */ + private Object readResolve() { + return ObjectUtils.NULL; + } + } + + + // Constants (LANG-816): + /* + These methods ensure constants are not inlined by javac. + For example, typically a developer might declare a constant like so: + + public final static int MAGIC_NUMBER = 5; + + Should a different jar file refer to this, and the MAGIC_NUMBER + is changed a later date (e.g., MAGIC_NUMBER = 6), the different jar + file will need to recompile itself. This is because javac + typically inlines the primitive or String constant directly into + the bytecode, and removes the reference to the MAGIC_NUMBER field. + + To help the other jar (so that it does not need to recompile + when constants are changed) the original developer can declare + their constant using one of the CONST() utility methods, instead: + + public final static int MAGIC_NUMBER = CONST(5); + */ + + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static boolean MAGIC_FLAG = ObjectUtils.CONST(true);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the boolean value to return + * @return the boolean v, unchanged + * @since 3.2 + */ + public static boolean CONST(final boolean v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static byte MAGIC_BYTE = ObjectUtils.CONST((byte) 127);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the byte value to return + * @return the byte v, unchanged + * @since 3.2 + */ + public static byte CONST(final byte v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static byte MAGIC_BYTE = ObjectUtils.CONST_BYTE(127);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the byte literal (as an int) value to return + * @throws IllegalArgumentException if the value passed to v + * is larger than a byte, that is, smaller than -128 or + * larger than 127. + * @return the byte v, unchanged + * @since 3.2 + */ + public static byte CONST_BYTE(final int v) throws IllegalArgumentException { + if (v < Byte.MIN_VALUE || v > Byte.MAX_VALUE) { + throw new IllegalArgumentException("Supplied value must be a valid byte literal between -128 and 127: [" + v + "]"); + } + return (byte) v; + } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static char MAGIC_CHAR = ObjectUtils.CONST('a');
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the char value to return + * @return the char v, unchanged + * @since 3.2 + */ + public static char CONST(final char v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static short MAGIC_SHORT = ObjectUtils.CONST((short) 123);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the short value to return + * @return the short v, unchanged + * @since 3.2 + */ + public static short CONST(final short v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static short MAGIC_SHORT = ObjectUtils.CONST_SHORT(127);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the short literal (as an int) value to return + * @throws IllegalArgumentException if the value passed to v + * is larger than a short, that is, smaller than -32768 or + * larger than 32767. + * @return the byte v, unchanged + * @since 3.2 + */ + public static short CONST_SHORT(final int v) throws IllegalArgumentException { + if (v < Short.MIN_VALUE || v > Short.MAX_VALUE) { + throw new IllegalArgumentException("Supplied value must be a valid byte literal between -32768 and 32767: [" + v + "]"); + } + return (short) v; + } + + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static int MAGIC_INT = ObjectUtils.CONST(123);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the int value to return + * @return the int v, unchanged + * @since 3.2 + */ + public static int CONST(final int v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static long MAGIC_LONG = ObjectUtils.CONST(123L);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the long value to return + * @return the long v, unchanged + * @since 3.2 + */ + public static long CONST(final long v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static float MAGIC_FLOAT = ObjectUtils.CONST(1.0f);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the float value to return + * @return the float v, unchanged + * @since 3.2 + */ + public static float CONST(final float v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static double MAGIC_DOUBLE = ObjectUtils.CONST(1.0);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the double value to return + * @return the double v, unchanged + * @since 3.2 + */ + public static double CONST(final double v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static String MAGIC_STRING = ObjectUtils.CONST("abc");
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param the Object type + * @param v the genericized Object value to return (typically a String). + * @return the genericized Object v, unchanged (typically a String). + * @since 3.2 + */ + public static T CONST(final T v) { return v; } + +} diff --git a/Java/commons-lang-ObjectUtils_123/metadata.json b/Java/commons-lang-ObjectUtils_123/metadata.json new file mode 100644 index 000000000..ad606e991 --- /dev/null +++ b/Java/commons-lang-ObjectUtils_123/metadata.json @@ -0,0 +1,21 @@ +{ + "language": "java", + "id": "commons-lang-ObjectUtils_123", + "buggyPath": ".", + "referencePath": null, + "buildCommand": "mvn package -V -B -Denforcer.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true -Drat.skip=true -Dlicense.skip=true -Dfindbugs.skip=true -Dgpg.skip=true -Dskip.npm=true -Dskip.gulp=true -Dskip.bower=true -Drat.numUnapprovedLicenses=100 -DskipTests=true -DskipITs=true -Dtest=None -DfailIfNoTests=false", + "testCommand": "mvn test -V -B -Denforcer.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true -Drat.skip=true -Dlicense.skip=true -Dfindbugs.skip=true -Dgpg.skip=true -Dskip.npm=true -Dskip.gulp=true -Dskip.bower=true -Drat.numUnapprovedLicenses=100", + "categories": [ + "safety", + "npe" + ], + "npe": { + "filepath": "src/main/java/org/apache/commons/lang3/ObjectUtils.java", + "line": 149, + "npe_method": "firstNonNull", + "deref_field": "val", + "npe_class": "ObjectUtils", + "repo": "commons-lang", + "bug_id": "ObjectUtils_123" + } +} diff --git a/Java/commons-lang-ObjectUtils_123/npe.json b/Java/commons-lang-ObjectUtils_123/npe.json new file mode 100644 index 000000000..9df16886b --- /dev/null +++ b/Java/commons-lang-ObjectUtils_123/npe.json @@ -0,0 +1,7 @@ +{ + "filepath": "src/main/java/org/apache/commons/lang3/ObjectUtils.java", + "line": 149, + "npe_method": "firstNonNull", + "deref_field": "val", + "npe_class": "ObjectUtils" +} \ No newline at end of file diff --git a/Java/commons-lang-ObjectUtils_184/Dockerfile b/Java/commons-lang-ObjectUtils_184/Dockerfile new file mode 100644 index 000000000..7b7fbe349 --- /dev/null +++ b/Java/commons-lang-ObjectUtils_184/Dockerfile @@ -0,0 +1,18 @@ +FROM ghcr.io/kupl/starlab-benchmarks/java-base:commons-lang + +ENV TZ=Asia/Seoul + +COPY ./metadata.json . +COPY ./npe.json . +COPY ./buggy.java /tmp/buggy.java +RUN export BUGGY_PATH=$(cat metadata.json | jq -r ".npe.filepath") \ + && export BUGGY_LINE=$(cat metadata.json | jq -r ".npe.line") \ + && export BUGGY_MTHD=$(cat metadata.json | jq -r ".npe.npe_method") \ + && mv /tmp/buggy.java $BUGGY_PATH \ + && echo "[{\"filepath\": \"$BUGGY_PATH\", \"line\": $BUGGY_LINE, \"method_name\": \"$BUGGY_MTHD\"}]" | jq . > traces.json + +RUN git init . && git add -A + +RUN $(cat metadata.json | jq -r ".buildCommand") + +RUN $(cat metadata.json | jq -r ".testCommand"); if [ $? -eq 0 ]; then exit 1; fi diff --git a/Java/commons-lang-ObjectUtils_184/buggy.java b/Java/commons-lang-ObjectUtils_184/buggy.java new file mode 100644 index 000000000..7656a0aab --- /dev/null +++ b/Java/commons-lang-ObjectUtils_184/buggy.java @@ -0,0 +1,1040 @@ +/* + * 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.Serializable; +import java.lang.reflect.Array; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.Map; +import java.util.TreeSet; + +import org.apache.commons.lang3.exception.CloneFailedException; +import org.apache.commons.lang3.mutable.MutableInt; +import org.apache.commons.lang3.text.StrBuilder; + +/** + *

Operations on {@code Object}.

+ * + *

This class tries to handle {@code null} input gracefully. + * An exception will generally not be thrown for a {@code null} input. + * Each method documents its behaviour in more detail.

+ * + *

#ThreadSafe#

+ * @since 1.0 + */ +//@Immutable +public class ObjectUtils { + + /** + *

Singleton used as a {@code null} placeholder where + * {@code null} has another meaning.

+ * + *

For example, in a {@code HashMap} the + * {@link java.util.HashMap#get(java.lang.Object)} method returns + * {@code null} if the {@code Map} contains {@code null} or if there + * is no matching key. The {@code Null} placeholder can be used to + * distinguish between these two cases.

+ * + *

Another example is {@code Hashtable}, where {@code null} + * cannot be stored.

+ * + *

This instance is Serializable.

+ */ + public static final Null NULL = new Null(); + + /** + *

{@code ObjectUtils} instances should NOT be constructed in + * standard programming. Instead, the static methods on the class should + * be used, such as {@code ObjectUtils.defaultIfNull("a","b");}.

+ * + *

This constructor is public to permit tools that require a JavaBean + * instance to operate.

+ */ + public ObjectUtils() { + super(); + } + + // Defaulting + //----------------------------------------------------------------------- + /** + *

Returns a default value if the object passed is {@code null}.

+ * + *
+     * ObjectUtils.defaultIfNull(null, null)      = null
+     * ObjectUtils.defaultIfNull(null, "")        = ""
+     * ObjectUtils.defaultIfNull(null, "zz")      = "zz"
+     * ObjectUtils.defaultIfNull("abc", *)        = "abc"
+     * ObjectUtils.defaultIfNull(Boolean.TRUE, *) = Boolean.TRUE
+     * 
+ * + * @param the type of the object + * @param object the {@code Object} to test, may be {@code null} + * @param defaultValue the default value to return, may be {@code null} + * @return {@code object} if it is not {@code null}, defaultValue otherwise + */ + public static T defaultIfNull(final T object, final T defaultValue) { + return object != null ? object : defaultValue; + } + + /** + *

Returns the first value in the array which is not {@code null}. + * If all the values are {@code null} or the array is {@code null} + * or empty then {@code null} is returned.

+ * + *
+     * ObjectUtils.firstNonNull(null, null)      = null
+     * ObjectUtils.firstNonNull(null, "")        = ""
+     * ObjectUtils.firstNonNull(null, null, "")  = ""
+     * ObjectUtils.firstNonNull(null, "zz")      = "zz"
+     * ObjectUtils.firstNonNull("abc", *)        = "abc"
+     * ObjectUtils.firstNonNull(null, "xyz", *)  = "xyz"
+     * ObjectUtils.firstNonNull(Boolean.TRUE, *) = Boolean.TRUE
+     * ObjectUtils.firstNonNull()                = null
+     * 
+ * + * @param the component type of the array + * @param values the values to test, may be {@code null} or empty + * @return the first value from {@code values} which is not {@code null}, + * or {@code null} if there are no non-null values + * @since 3.0 + */ + public static T firstNonNull(final T... values) { + if (values != null) { + for (final T val : values) { + if (val != null) { + return val; + } + } + } + return null; + } + + /** + * Checks if any value in the given array is not {@code null}. + * + *

+ * If all the values are {@code null} or the array is {@code null} + * or empty then {@code false} is returned. Otherwise {@code true} is returned. + *

+ * + *
+     * ObjectUtils.anyNotNull(*)                = true
+     * ObjectUtils.anyNotNull(*, null)          = true
+     * ObjectUtils.anyNotNull(null, *)          = true
+     * ObjectUtils.anyNotNull(null, null, *, *) = true
+     * ObjectUtils.anyNotNull(null)             = false
+     * ObjectUtils.anyNotNull(null, null)       = false
+     * 
+ * + * @param values the values to test, may be {@code null} or empty + * @return {@code true} if there is at least one non-null value in the array, + * {@code false} if all values in the array are {@code null}s. + * If the array is {@code null} or empty {@code false} is also returned. + * @since 3.5 + */ + public static boolean anyNotNull(final Object... values) { + return firstNonNull(values) != null; + } + + /** + * Checks if all values in the array are not {@code nulls}. + * + *

+ * If any value is {@code null} or the array is {@code null} then + * {@code false} is returned. If all elements in array are not + * {@code null} or the array is empty (contains no elements) {@code true} + * is returned. + *

+ * + *
+     * ObjectUtils.allNotNull(*)             = true
+     * ObjectUtils.allNotNull(*, *)          = true
+     * ObjectUtils.allNotNull(null)          = false
+     * ObjectUtils.allNotNull(null, null)    = false
+     * ObjectUtils.allNotNull(null, *)       = false
+     * ObjectUtils.allNotNull(*, null)       = false
+     * ObjectUtils.allNotNull(*, *, null, *) = false
+     * 
+ * + * @param values the values to test, may be {@code null} or empty + * @return {@code false} if there is at least one {@code null} value in the array or the array is {@code null}, + * {@code true} if all values in the array are not {@code null}s or array contains no elements. + * @since 3.5 + */ +/** + * Checks if all values in the array are not {@code nulls}. + * + *

+ * If any value is {@code null} or the array is {@code null} then + * {@code false} is returned. If all elements in array are not + * {@code null} or the array is empty (contains no elements) {@code true} + * is returned. + *

+ * + *
+ * ObjectUtils.allNotNull(*)             = true
+ * ObjectUtils.allNotNull(*, *)          = true
+ * ObjectUtils.allNotNull(null)          = false
+ * ObjectUtils.allNotNull(null, null)    = false
+ * ObjectUtils.allNotNull(null, *)       = false
+ * ObjectUtils.allNotNull(*, null)       = false
+ * ObjectUtils.allNotNull(*, *, null, *) = false
+ * 
+ * + * @param values + * the values to test, may be {@code null} or empty + * @return {@code false} if there is at least one {@code null} value in the array or the array is {@code null}, +{@code true} if all values in the array are not {@code null}s or array contains no elements. + * @since 3.5 + */ +public static boolean allNotNull(final java.lang.Object... values) { + { + for (final java.lang.Object val : /* NPEX_NULL_EXP */ + values) { + if (val == null) { + return false; + } + } + return true; + } +} + + // Null-safe equals/hashCode + //----------------------------------------------------------------------- + /** + *

Compares two objects for equality, where either one or both + * objects may be {@code null}.

+ * + *
+     * ObjectUtils.equals(null, null)                  = true
+     * ObjectUtils.equals(null, "")                    = false
+     * ObjectUtils.equals("", null)                    = false
+     * ObjectUtils.equals("", "")                      = true
+     * ObjectUtils.equals(Boolean.TRUE, null)          = false
+     * ObjectUtils.equals(Boolean.TRUE, "true")        = false
+     * ObjectUtils.equals(Boolean.TRUE, Boolean.TRUE)  = true
+     * ObjectUtils.equals(Boolean.TRUE, Boolean.FALSE) = false
+     * 
+ * + * @param object1 the first object, may be {@code null} + * @param object2 the second object, may be {@code null} + * @return {@code true} if the values of both objects are the same + * @deprecated this method has been replaced by {@code java.util.Objects.equals(Object, Object)} in Java 7 and will + * be removed from future releases. + */ + @Deprecated + public static boolean equals(final Object object1, final Object object2) { + if (object1 == object2) { + return true; + } + if (object1 == null || object2 == null) { + return false; + } + return object1.equals(object2); + } + + /** + *

Compares two objects for inequality, where either one or both + * objects may be {@code null}.

+ * + *
+     * ObjectUtils.notEqual(null, null)                  = false
+     * ObjectUtils.notEqual(null, "")                    = true
+     * ObjectUtils.notEqual("", null)                    = true
+     * ObjectUtils.notEqual("", "")                      = false
+     * ObjectUtils.notEqual(Boolean.TRUE, null)          = true
+     * ObjectUtils.notEqual(Boolean.TRUE, "true")        = true
+     * ObjectUtils.notEqual(Boolean.TRUE, Boolean.TRUE)  = false
+     * ObjectUtils.notEqual(Boolean.TRUE, Boolean.FALSE) = true
+     * 
+ * + * @param object1 the first object, may be {@code null} + * @param object2 the second object, may be {@code null} + * @return {@code false} if the values of both objects are the same + */ + public static boolean notEqual(final Object object1, final Object object2) { + return ObjectUtils.equals(object1, object2) == false; + } + + /** + *

Gets the hash code of an object returning zero when the + * object is {@code null}.

+ * + *
+     * ObjectUtils.hashCode(null)   = 0
+     * ObjectUtils.hashCode(obj)    = obj.hashCode()
+     * 
+ * + * @param obj the object to obtain the hash code of, may be {@code null} + * @return the hash code of the object, or zero if null + * @since 2.1 + * @deprecated this method has been replaced by {@code java.util.Objects.hashCode(Object)} in Java 7 and will be + * removed in future releases + */ + @Deprecated + public static int hashCode(final Object obj) { + // hashCode(Object) retained for performance, as hash code is often critical + return obj == null ? 0 : obj.hashCode(); + } + + /** + *

Gets the hash code for multiple objects.

+ * + *

This allows a hash code to be rapidly calculated for a number of objects. + * The hash code for a single object is the not same as {@link #hashCode(Object)}. + * The hash code for multiple objects is the same as that calculated by an + * {@code ArrayList} containing the specified objects.

+ * + *
+     * ObjectUtils.hashCodeMulti()                 = 1
+     * ObjectUtils.hashCodeMulti((Object[]) null)  = 1
+     * ObjectUtils.hashCodeMulti(a)                = 31 + a.hashCode()
+     * ObjectUtils.hashCodeMulti(a,b)              = (31 + a.hashCode()) * 31 + b.hashCode()
+     * ObjectUtils.hashCodeMulti(a,b,c)            = ((31 + a.hashCode()) * 31 + b.hashCode()) * 31 + c.hashCode()
+     * 
+ * + * @param objects the objects to obtain the hash code of, may be {@code null} + * @return the hash code of the objects, or zero if null + * @since 3.0 + * @deprecated this method has been replaced by {@code java.util.Objects.hash(Object...)} in Java 7 and will be + * removed in future releases. + */ + @Deprecated + public static int hashCodeMulti(final Object... objects) { + int hash = 1; + if (objects != null) { + for (final Object object : objects) { + final int tmpHash = ObjectUtils.hashCode(object); + hash = hash * 31 + tmpHash; + } + } + return hash; + } + + // Identity ToString + //----------------------------------------------------------------------- + /** + *

Gets the toString that would be produced by {@code Object} + * if a class did not override toString itself. {@code null} + * will return {@code null}.

+ * + *
+     * ObjectUtils.identityToString(null)         = null
+     * ObjectUtils.identityToString("")           = "java.lang.String@1e23"
+     * ObjectUtils.identityToString(Boolean.TRUE) = "java.lang.Boolean@7fa"
+     * 
+ * + * @param object the object to create a toString for, may be + * {@code null} + * @return the default toString text, or {@code null} if + * {@code null} passed in + */ + public static String identityToString(final Object object) { + if (object == null) { + return null; + } + final StringBuilder builder = new StringBuilder(); + identityToString(builder, object); + return builder.toString(); + } + + /** + *

Appends the toString that would be produced by {@code Object} + * if a class did not override toString itself. {@code null} + * will throw a NullPointerException for either of the two parameters.

+ * + *
+     * ObjectUtils.identityToString(appendable, "")            = appendable.append("java.lang.String@1e23"
+     * ObjectUtils.identityToString(appendable, Boolean.TRUE)  = appendable.append("java.lang.Boolean@7fa"
+     * ObjectUtils.identityToString(appendable, Boolean.TRUE)  = appendable.append("java.lang.Boolean@7fa")
+     * 
+ * + * @param appendable the appendable to append to + * @param object the object to create a toString for + * @throws IOException if an I/O error occurs + * @since 3.2 + */ + public static void identityToString(final Appendable appendable, final Object object) throws IOException { + if (object == null) { + throw new NullPointerException("Cannot get the toString of a null identity"); + } + appendable.append(object.getClass().getName()) + .append('@') + .append(Integer.toHexString(System.identityHashCode(object))); + } + + /** + *

Appends the toString that would be produced by {@code Object} + * if a class did not override toString itself. {@code null} + * will throw a NullPointerException for either of the two parameters.

+ * + *
+     * ObjectUtils.identityToString(builder, "")            = builder.append("java.lang.String@1e23"
+     * ObjectUtils.identityToString(builder, Boolean.TRUE)  = builder.append("java.lang.Boolean@7fa"
+     * ObjectUtils.identityToString(builder, Boolean.TRUE)  = builder.append("java.lang.Boolean@7fa")
+     * 
+ * + * @param builder the builder to append to + * @param object the object to create a toString for + * @since 3.2 + */ + public static void identityToString(final StrBuilder builder, final Object object) { + if (object == null) { + throw new NullPointerException("Cannot get the toString of a null identity"); + } + builder.append(object.getClass().getName()) + .append('@') + .append(Integer.toHexString(System.identityHashCode(object))); + } + + /** + *

Appends the toString that would be produced by {@code Object} + * if a class did not override toString itself. {@code null} + * will throw a NullPointerException for either of the two parameters.

+ * + *
+     * ObjectUtils.identityToString(buf, "")            = buf.append("java.lang.String@1e23"
+     * ObjectUtils.identityToString(buf, Boolean.TRUE)  = buf.append("java.lang.Boolean@7fa"
+     * ObjectUtils.identityToString(buf, Boolean.TRUE)  = buf.append("java.lang.Boolean@7fa")
+     * 
+ * + * @param buffer the buffer to append to + * @param object the object to create a toString for + * @since 2.4 + */ + public static void identityToString(final StringBuffer buffer, final Object object) { + if (object == null) { + throw new NullPointerException("Cannot get the toString of a null identity"); + } + buffer.append(object.getClass().getName()) + .append('@') + .append(Integer.toHexString(System.identityHashCode(object))); + } + + /** + *

Appends the toString that would be produced by {@code Object} + * if a class did not override toString itself. {@code null} + * will throw a NullPointerException for either of the two parameters.

+ * + *
+     * ObjectUtils.identityToString(builder, "")            = builder.append("java.lang.String@1e23"
+     * ObjectUtils.identityToString(builder, Boolean.TRUE)  = builder.append("java.lang.Boolean@7fa"
+     * ObjectUtils.identityToString(builder, Boolean.TRUE)  = builder.append("java.lang.Boolean@7fa")
+     * 
+ * + * @param builder the builder to append to + * @param object the object to create a toString for + * @since 3.2 + */ + public static void identityToString(final StringBuilder builder, final Object object) { + if (object == null) { + throw new NullPointerException("Cannot get the toString of a null identity"); + } + builder.append(object.getClass().getName()) + .append('@') + .append(Integer.toHexString(System.identityHashCode(object))); + } + + // ToString + //----------------------------------------------------------------------- + /** + *

Gets the {@code toString} of an {@code Object} returning + * an empty string ("") if {@code null} input.

+ * + *
+     * ObjectUtils.toString(null)         = ""
+     * ObjectUtils.toString("")           = ""
+     * ObjectUtils.toString("bat")        = "bat"
+     * ObjectUtils.toString(Boolean.TRUE) = "true"
+     * 
+ * + * @see StringUtils#defaultString(String) + * @see String#valueOf(Object) + * @param obj the Object to {@code toString}, may be null + * @return the passed in Object's toString, or {@code ""} if {@code null} input + * @since 2.0 + * @deprecated this method has been replaced by {@code java.util.Objects.toString(Object)} in Java 7 and will be + * removed in future releases. Note however that said method will return "null" for null references, while this + * method returns and empty String. To preserve behavior use {@code java.util.Objects.toString(myObject, "")} + */ + @Deprecated + public static String toString(final Object obj) { + return obj == null ? StringUtils.EMPTY : obj.toString(); + } + + /** + *

Gets the {@code toString} of an {@code Object} returning + * a specified text if {@code null} input.

+ * + *
+     * ObjectUtils.toString(null, null)           = null
+     * ObjectUtils.toString(null, "null")         = "null"
+     * ObjectUtils.toString("", "null")           = ""
+     * ObjectUtils.toString("bat", "null")        = "bat"
+     * ObjectUtils.toString(Boolean.TRUE, "null") = "true"
+     * 
+ * + * @see StringUtils#defaultString(String,String) + * @see String#valueOf(Object) + * @param obj the Object to {@code toString}, may be null + * @param nullStr the String to return if {@code null} input, may be null + * @return the passed in Object's toString, or {@code nullStr} if {@code null} input + * @since 2.0 + * @deprecated this method has been replaced by {@code java.util.Objects.toString(Object, String)} in Java 7 and + * will be removed in future releases. + */ + @Deprecated + public static String toString(final Object obj, final String nullStr) { + return obj == null ? nullStr : obj.toString(); + } + + // Comparable + //----------------------------------------------------------------------- + /** + *

Null safe comparison of Comparables.

+ * + * @param type of the values processed by this method + * @param values the set of comparable values, may be null + * @return + *
    + *
  • If any objects are non-null and unequal, the lesser object. + *
  • If all objects are non-null and equal, the first. + *
  • If any of the comparables are null, the lesser of the non-null objects. + *
  • If all the comparables are null, null is returned. + *
+ */ + public static > T min(final T... values) { + T result = null; + if (values != null) { + for (final T value : values) { + if (compare(value, result, true) < 0) { + result = value; + } + } + } + return result; + } + + /** + *

Null safe comparison of Comparables.

+ * + * @param type of the values processed by this method + * @param values the set of comparable values, may be null + * @return + *
    + *
  • If any objects are non-null and unequal, the greater object. + *
  • If all objects are non-null and equal, the first. + *
  • If any of the comparables are null, the greater of the non-null objects. + *
  • If all the comparables are null, null is returned. + *
+ */ + public static > T max(final T... values) { + T result = null; + if (values != null) { + for (final T value : values) { + if (compare(value, result, false) > 0) { + result = value; + } + } + } + return result; + } + + /** + *

Null safe comparison of Comparables. + * {@code null} is assumed to be less than a non-{@code null} value.

+ * + * @param type of the values processed by this method + * @param c1 the first comparable, may be null + * @param c2 the second comparable, may be null + * @return a negative value if c1 < c2, zero if c1 = c2 + * and a positive value if c1 > c2 + */ + public static > int compare(final T c1, final T c2) { + return compare(c1, c2, false); + } + + /** + *

Null safe comparison of Comparables.

+ * + * @param type of the values processed by this method + * @param c1 the first comparable, may be null + * @param c2 the second comparable, may be null + * @param nullGreater if true {@code null} is considered greater + * than a non-{@code null} value or if false {@code null} is + * considered less than a Non-{@code null} value + * @return a negative value if c1 < c2, zero if c1 = c2 + * and a positive value if c1 > c2 + * @see java.util.Comparator#compare(Object, Object) + */ + public static > int compare(final T c1, final T c2, final boolean nullGreater) { + if (c1 == c2) { + return 0; + } else if (c1 == null) { + return nullGreater ? 1 : -1; + } else if (c2 == null) { + return nullGreater ? -1 : 1; + } + return c1.compareTo(c2); + } + + /** + * Find the "best guess" middle value among comparables. If there is an even + * number of total values, the lower of the two middle values will be returned. + * @param type of values processed by this method + * @param items to compare + * @return T at middle position + * @throws NullPointerException if items is {@code null} + * @throws IllegalArgumentException if items is empty or contains {@code null} values + * @since 3.0.1 + */ + public static > T median(final T... items) { + Validate.notEmpty(items); + Validate.noNullElements(items); + final TreeSet sort = new TreeSet(); + Collections.addAll(sort, items); + @SuppressWarnings("unchecked") //we know all items added were T instances + final + T result = (T) sort.toArray()[(sort.size() - 1) / 2]; + return result; + } + + /** + * Find the "best guess" middle value among comparables. If there is an even + * number of total values, the lower of the two middle values will be returned. + * @param type of values processed by this method + * @param comparator to use for comparisons + * @param items to compare + * @return T at middle position + * @throws NullPointerException if items or comparator is {@code null} + * @throws IllegalArgumentException if items is empty or contains {@code null} values + * @since 3.0.1 + */ + public static T median(final Comparator comparator, final T... items) { + Validate.notEmpty(items, "null/empty items"); + Validate.noNullElements(items); + Validate.notNull(comparator, "null comparator"); + final TreeSet sort = new TreeSet(comparator); + Collections.addAll(sort, items); + @SuppressWarnings("unchecked") //we know all items added were T instances + final + T result = (T) sort.toArray()[(sort.size() - 1) / 2]; + return result; + } + + // Mode + //----------------------------------------------------------------------- + /** + * Find the most frequently occurring item. + * + * @param type of values processed by this method + * @param items to check + * @return most populous T, {@code null} if non-unique or no items supplied + * @since 3.0.1 + */ + public static T mode(final T... items) { + if (ArrayUtils.isNotEmpty(items)) { + final HashMap occurrences = new HashMap(items.length); + for (final T t : items) { + final MutableInt count = occurrences.get(t); + if (count == null) { + occurrences.put(t, new MutableInt(1)); + } else { + count.increment(); + } + } + T result = null; + int max = 0; + for (final Map.Entry e : occurrences.entrySet()) { + final int cmp = e.getValue().intValue(); + if (cmp == max) { + result = null; + } else if (cmp > max) { + max = cmp; + result = e.getKey(); + } + } + return result; + } + return null; + } + + // cloning + //----------------------------------------------------------------------- + /** + *

Clone an object.

+ * + * @param the type of the object + * @param obj the object to clone, null returns null + * @return the clone if the object implements {@link Cloneable} otherwise {@code null} + * @throws CloneFailedException if the object is cloneable and the clone operation fails + * @since 3.0 + */ + public static T clone(final T obj) { + if (obj instanceof Cloneable) { + final Object result; + if (obj.getClass().isArray()) { + final Class componentType = obj.getClass().getComponentType(); + if (!componentType.isPrimitive()) { + result = ((Object[]) obj).clone(); + } else { + int length = Array.getLength(obj); + result = Array.newInstance(componentType, length); + while (length-- > 0) { + Array.set(result, length, Array.get(obj, length)); + } + } + } else { + try { + final Method clone = obj.getClass().getMethod("clone"); + result = clone.invoke(obj); + } catch (final NoSuchMethodException e) { + throw new CloneFailedException("Cloneable type " + + obj.getClass().getName() + + " has no clone method", e); + } catch (final IllegalAccessException e) { + throw new CloneFailedException("Cannot clone Cloneable type " + + obj.getClass().getName(), e); + } catch (final InvocationTargetException e) { + throw new CloneFailedException("Exception cloning Cloneable type " + + obj.getClass().getName(), e.getCause()); + } + } + @SuppressWarnings("unchecked") // OK because input is of type T + final T checked = (T) result; + return checked; + } + + return null; + } + + /** + *

Clone an object if possible.

+ * + *

This method is similar to {@link #clone(Object)}, but will return the provided + * instance as the return value instead of {@code null} if the instance + * is not cloneable. This is more convenient if the caller uses different + * implementations (e.g. of a service) and some of the implementations do not allow concurrent + * processing or have state. In such cases the implementation can simply provide a proper + * clone implementation and the caller's code does not have to change.

+ * + * @param the type of the object + * @param obj the object to clone, null returns null + * @return the clone if the object implements {@link Cloneable} otherwise the object itself + * @throws CloneFailedException if the object is cloneable and the clone operation fails + * @since 3.0 + */ + public static T cloneIfPossible(final T obj) { + final T clone = clone(obj); + return clone == null ? obj : clone; + } + + // Null + //----------------------------------------------------------------------- + /** + *

Class used as a null placeholder where {@code null} + * has another meaning.

+ * + *

For example, in a {@code HashMap} the + * {@link java.util.HashMap#get(java.lang.Object)} method returns + * {@code null} if the {@code Map} contains {@code null} or if there is + * no matching key. The {@code Null} placeholder can be used to distinguish + * between these two cases.

+ * + *

Another example is {@code Hashtable}, where {@code null} + * cannot be stored.

+ */ + public static class Null implements Serializable { + /** + * Required for serialization support. Declare serialization compatibility with Commons Lang 1.0 + * + * @see java.io.Serializable + */ + private static final long serialVersionUID = 7092611880189329093L; + + /** + * Restricted constructor - singleton. + */ + Null() { + super(); + } + + /** + *

Ensure singleton.

+ * + * @return the singleton value + */ + private Object readResolve() { + return ObjectUtils.NULL; + } + } + + + // Constants (LANG-816): + /* + These methods ensure constants are not inlined by javac. + For example, typically a developer might declare a constant like so: + + public final static int MAGIC_NUMBER = 5; + + Should a different jar file refer to this, and the MAGIC_NUMBER + is changed a later date (e.g., MAGIC_NUMBER = 6), the different jar + file will need to recompile itself. This is because javac + typically inlines the primitive or String constant directly into + the bytecode, and removes the reference to the MAGIC_NUMBER field. + + To help the other jar (so that it does not need to recompile + when constants are changed) the original developer can declare + their constant using one of the CONST() utility methods, instead: + + public final static int MAGIC_NUMBER = CONST(5); + */ + + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static boolean MAGIC_FLAG = ObjectUtils.CONST(true);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the boolean value to return + * @return the boolean v, unchanged + * @since 3.2 + */ + public static boolean CONST(final boolean v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static byte MAGIC_BYTE = ObjectUtils.CONST((byte) 127);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the byte value to return + * @return the byte v, unchanged + * @since 3.2 + */ + public static byte CONST(final byte v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static byte MAGIC_BYTE = ObjectUtils.CONST_BYTE(127);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the byte literal (as an int) value to return + * @throws IllegalArgumentException if the value passed to v + * is larger than a byte, that is, smaller than -128 or + * larger than 127. + * @return the byte v, unchanged + * @since 3.2 + */ + public static byte CONST_BYTE(final int v) throws IllegalArgumentException { + if (v < Byte.MIN_VALUE || v > Byte.MAX_VALUE) { + throw new IllegalArgumentException("Supplied value must be a valid byte literal between -128 and 127: [" + v + "]"); + } + return (byte) v; + } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static char MAGIC_CHAR = ObjectUtils.CONST('a');
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the char value to return + * @return the char v, unchanged + * @since 3.2 + */ + public static char CONST(final char v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static short MAGIC_SHORT = ObjectUtils.CONST((short) 123);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the short value to return + * @return the short v, unchanged + * @since 3.2 + */ + public static short CONST(final short v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static short MAGIC_SHORT = ObjectUtils.CONST_SHORT(127);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the short literal (as an int) value to return + * @throws IllegalArgumentException if the value passed to v + * is larger than a short, that is, smaller than -32768 or + * larger than 32767. + * @return the byte v, unchanged + * @since 3.2 + */ + public static short CONST_SHORT(final int v) throws IllegalArgumentException { + if (v < Short.MIN_VALUE || v > Short.MAX_VALUE) { + throw new IllegalArgumentException("Supplied value must be a valid byte literal between -32768 and 32767: [" + v + "]"); + } + return (short) v; + } + + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static int MAGIC_INT = ObjectUtils.CONST(123);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the int value to return + * @return the int v, unchanged + * @since 3.2 + */ + public static int CONST(final int v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static long MAGIC_LONG = ObjectUtils.CONST(123L);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the long value to return + * @return the long v, unchanged + * @since 3.2 + */ + public static long CONST(final long v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static float MAGIC_FLOAT = ObjectUtils.CONST(1.0f);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the float value to return + * @return the float v, unchanged + * @since 3.2 + */ + public static float CONST(final float v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static double MAGIC_DOUBLE = ObjectUtils.CONST(1.0);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the double value to return + * @return the double v, unchanged + * @since 3.2 + */ + public static double CONST(final double v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static String MAGIC_STRING = ObjectUtils.CONST("abc");
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param the Object type + * @param v the genericized Object value to return (typically a String). + * @return the genericized Object v, unchanged (typically a String). + * @since 3.2 + */ + public static T CONST(final T v) { return v; } + +} diff --git a/Java/commons-lang-ObjectUtils_184/metadata.json b/Java/commons-lang-ObjectUtils_184/metadata.json new file mode 100644 index 000000000..310884463 --- /dev/null +++ b/Java/commons-lang-ObjectUtils_184/metadata.json @@ -0,0 +1,21 @@ +{ + "language": "java", + "id": "commons-lang-ObjectUtils_184", + "buggyPath": ".", + "referencePath": null, + "buildCommand": "mvn package -V -B -Denforcer.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true -Drat.skip=true -Dlicense.skip=true -Dfindbugs.skip=true -Dgpg.skip=true -Dskip.npm=true -Dskip.gulp=true -Dskip.bower=true -Drat.numUnapprovedLicenses=100 -DskipTests=true -DskipITs=true -Dtest=None -DfailIfNoTests=false", + "testCommand": "mvn test -V -B -Denforcer.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true -Drat.skip=true -Dlicense.skip=true -Dfindbugs.skip=true -Dgpg.skip=true -Dskip.npm=true -Dskip.gulp=true -Dskip.bower=true -Drat.numUnapprovedLicenses=100", + "categories": [ + "safety", + "npe" + ], + "npe": { + "filepath": "src/main/java/org/apache/commons/lang3/ObjectUtils.java", + "line": 212, + "npe_method": "allNotNull", + "deref_field": "values", + "npe_class": "ObjectUtils", + "repo": "commons-lang", + "bug_id": "ObjectUtils_184" + } +} diff --git a/Java/commons-lang-ObjectUtils_184/npe.json b/Java/commons-lang-ObjectUtils_184/npe.json new file mode 100644 index 000000000..4b438502e --- /dev/null +++ b/Java/commons-lang-ObjectUtils_184/npe.json @@ -0,0 +1,7 @@ +{ + "filepath": "src/main/java/org/apache/commons/lang3/ObjectUtils.java", + "line": 212, + "npe_method": "allNotNull", + "deref_field": "values", + "npe_class": "ObjectUtils" +} \ No newline at end of file diff --git a/Java/commons-lang-ObjectUtils_272/Dockerfile b/Java/commons-lang-ObjectUtils_272/Dockerfile new file mode 100644 index 000000000..7b7fbe349 --- /dev/null +++ b/Java/commons-lang-ObjectUtils_272/Dockerfile @@ -0,0 +1,18 @@ +FROM ghcr.io/kupl/starlab-benchmarks/java-base:commons-lang + +ENV TZ=Asia/Seoul + +COPY ./metadata.json . +COPY ./npe.json . +COPY ./buggy.java /tmp/buggy.java +RUN export BUGGY_PATH=$(cat metadata.json | jq -r ".npe.filepath") \ + && export BUGGY_LINE=$(cat metadata.json | jq -r ".npe.line") \ + && export BUGGY_MTHD=$(cat metadata.json | jq -r ".npe.npe_method") \ + && mv /tmp/buggy.java $BUGGY_PATH \ + && echo "[{\"filepath\": \"$BUGGY_PATH\", \"line\": $BUGGY_LINE, \"method_name\": \"$BUGGY_MTHD\"}]" | jq . > traces.json + +RUN git init . && git add -A + +RUN $(cat metadata.json | jq -r ".buildCommand") + +RUN $(cat metadata.json | jq -r ".testCommand"); if [ $? -eq 0 ]; then exit 1; fi diff --git a/Java/commons-lang-ObjectUtils_272/buggy.java b/Java/commons-lang-ObjectUtils_272/buggy.java new file mode 100644 index 000000000..c75e486ff --- /dev/null +++ b/Java/commons-lang-ObjectUtils_272/buggy.java @@ -0,0 +1,1033 @@ +/* + * 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.Serializable; +import java.lang.reflect.Array; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.Map; +import java.util.TreeSet; + +import org.apache.commons.lang3.exception.CloneFailedException; +import org.apache.commons.lang3.mutable.MutableInt; +import org.apache.commons.lang3.text.StrBuilder; + +/** + *

Operations on {@code Object}.

+ * + *

This class tries to handle {@code null} input gracefully. + * An exception will generally not be thrown for a {@code null} input. + * Each method documents its behaviour in more detail.

+ * + *

#ThreadSafe#

+ * @since 1.0 + */ +//@Immutable +public class ObjectUtils { + + /** + *

Singleton used as a {@code null} placeholder where + * {@code null} has another meaning.

+ * + *

For example, in a {@code HashMap} the + * {@link java.util.HashMap#get(java.lang.Object)} method returns + * {@code null} if the {@code Map} contains {@code null} or if there + * is no matching key. The {@code Null} placeholder can be used to + * distinguish between these two cases.

+ * + *

Another example is {@code Hashtable}, where {@code null} + * cannot be stored.

+ * + *

This instance is Serializable.

+ */ + public static final Null NULL = new Null(); + + /** + *

{@code ObjectUtils} instances should NOT be constructed in + * standard programming. Instead, the static methods on the class should + * be used, such as {@code ObjectUtils.defaultIfNull("a","b");}.

+ * + *

This constructor is public to permit tools that require a JavaBean + * instance to operate.

+ */ + public ObjectUtils() { + super(); + } + + // Defaulting + //----------------------------------------------------------------------- + /** + *

Returns a default value if the object passed is {@code null}.

+ * + *
+     * ObjectUtils.defaultIfNull(null, null)      = null
+     * ObjectUtils.defaultIfNull(null, "")        = ""
+     * ObjectUtils.defaultIfNull(null, "zz")      = "zz"
+     * ObjectUtils.defaultIfNull("abc", *)        = "abc"
+     * ObjectUtils.defaultIfNull(Boolean.TRUE, *) = Boolean.TRUE
+     * 
+ * + * @param the type of the object + * @param object the {@code Object} to test, may be {@code null} + * @param defaultValue the default value to return, may be {@code null} + * @return {@code object} if it is not {@code null}, defaultValue otherwise + */ + public static T defaultIfNull(final T object, final T defaultValue) { + return object != null ? object : defaultValue; + } + + /** + *

Returns the first value in the array which is not {@code null}. + * If all the values are {@code null} or the array is {@code null} + * or empty then {@code null} is returned.

+ * + *
+     * ObjectUtils.firstNonNull(null, null)      = null
+     * ObjectUtils.firstNonNull(null, "")        = ""
+     * ObjectUtils.firstNonNull(null, null, "")  = ""
+     * ObjectUtils.firstNonNull(null, "zz")      = "zz"
+     * ObjectUtils.firstNonNull("abc", *)        = "abc"
+     * ObjectUtils.firstNonNull(null, "xyz", *)  = "xyz"
+     * ObjectUtils.firstNonNull(Boolean.TRUE, *) = Boolean.TRUE
+     * ObjectUtils.firstNonNull()                = null
+     * 
+ * + * @param the component type of the array + * @param values the values to test, may be {@code null} or empty + * @return the first value from {@code values} which is not {@code null}, + * or {@code null} if there are no non-null values + * @since 3.0 + */ + public static T firstNonNull(final T... values) { + if (values != null) { + for (final T val : values) { + if (val != null) { + return val; + } + } + } + return null; + } + + /** + * Checks if any value in the given array is not {@code null}. + * + *

+ * If all the values are {@code null} or the array is {@code null} + * or empty then {@code false} is returned. Otherwise {@code true} is returned. + *

+ * + *
+     * ObjectUtils.anyNotNull(*)                = true
+     * ObjectUtils.anyNotNull(*, null)          = true
+     * ObjectUtils.anyNotNull(null, *)          = true
+     * ObjectUtils.anyNotNull(null, null, *, *) = true
+     * ObjectUtils.anyNotNull(null)             = false
+     * ObjectUtils.anyNotNull(null, null)       = false
+     * 
+ * + * @param values the values to test, may be {@code null} or empty + * @return {@code true} if there is at least one non-null value in the array, + * {@code false} if all values in the array are {@code null}s. + * If the array is {@code null} or empty {@code false} is also returned. + * @since 3.5 + */ + public static boolean anyNotNull(final Object... values) { + return firstNonNull(values) != null; + } + + /** + * Checks if all values in the array are not {@code nulls}. + * + *

+ * If any value is {@code null} or the array is {@code null} then + * {@code false} is returned. If all elements in array are not + * {@code null} or the array is empty (contains no elements) {@code true} + * is returned. + *

+ * + *
+     * ObjectUtils.allNotNull(*)             = true
+     * ObjectUtils.allNotNull(*, *)          = true
+     * ObjectUtils.allNotNull(null)          = false
+     * ObjectUtils.allNotNull(null, null)    = false
+     * ObjectUtils.allNotNull(null, *)       = false
+     * ObjectUtils.allNotNull(*, null)       = false
+     * ObjectUtils.allNotNull(*, *, null, *) = false
+     * 
+ * + * @param values the values to test, may be {@code null} or empty + * @return {@code false} if there is at least one {@code null} value in the array or the array is {@code null}, + * {@code true} if all values in the array are not {@code null}s or array contains no elements. + * @since 3.5 + */ + public static boolean allNotNull(final Object... values) { + if (values == null) { + return false; + } + + for (final Object val : values) { + if (val == null) { + return false; + } + } + + return true; + } + + // Null-safe equals/hashCode + //----------------------------------------------------------------------- + /** + *

Compares two objects for equality, where either one or both + * objects may be {@code null}.

+ * + *
+     * ObjectUtils.equals(null, null)                  = true
+     * ObjectUtils.equals(null, "")                    = false
+     * ObjectUtils.equals("", null)                    = false
+     * ObjectUtils.equals("", "")                      = true
+     * ObjectUtils.equals(Boolean.TRUE, null)          = false
+     * ObjectUtils.equals(Boolean.TRUE, "true")        = false
+     * ObjectUtils.equals(Boolean.TRUE, Boolean.TRUE)  = true
+     * ObjectUtils.equals(Boolean.TRUE, Boolean.FALSE) = false
+     * 
+ * + * @param object1 the first object, may be {@code null} + * @param object2 the second object, may be {@code null} + * @return {@code true} if the values of both objects are the same + * @deprecated this method has been replaced by {@code java.util.Objects.equals(Object, Object)} in Java 7 and will + * be removed from future releases. + */ + @Deprecated + public static boolean equals(final Object object1, final Object object2) { + if (object1 == object2) { + return true; + } + if (object1 == null || object2 == null) { + return false; + } + return object1.equals(object2); + } + + /** + *

Compares two objects for inequality, where either one or both + * objects may be {@code null}.

+ * + *
+     * ObjectUtils.notEqual(null, null)                  = false
+     * ObjectUtils.notEqual(null, "")                    = true
+     * ObjectUtils.notEqual("", null)                    = true
+     * ObjectUtils.notEqual("", "")                      = false
+     * ObjectUtils.notEqual(Boolean.TRUE, null)          = true
+     * ObjectUtils.notEqual(Boolean.TRUE, "true")        = true
+     * ObjectUtils.notEqual(Boolean.TRUE, Boolean.TRUE)  = false
+     * ObjectUtils.notEqual(Boolean.TRUE, Boolean.FALSE) = true
+     * 
+ * + * @param object1 the first object, may be {@code null} + * @param object2 the second object, may be {@code null} + * @return {@code false} if the values of both objects are the same + */ + public static boolean notEqual(final Object object1, final Object object2) { + return ObjectUtils.equals(object1, object2) == false; + } + + /** + *

Gets the hash code of an object returning zero when the + * object is {@code null}.

+ * + *
+     * ObjectUtils.hashCode(null)   = 0
+     * ObjectUtils.hashCode(obj)    = obj.hashCode()
+     * 
+ * + * @param obj the object to obtain the hash code of, may be {@code null} + * @return the hash code of the object, or zero if null + * @since 2.1 + * @deprecated this method has been replaced by {@code java.util.Objects.hashCode(Object)} in Java 7 and will be + * removed in future releases + */ + @Deprecated +/** + *

Gets the hash code of an object returning zero when the + * object is {@code null}.

+ * + *
+ * ObjectUtils.hashCode(null)   = 0
+ * ObjectUtils.hashCode(obj)    = obj.hashCode()
+ * 
+ * + * @param obj + * the object to obtain the hash code of, may be {@code null} + * @return the hash code of the object, or zero if null + * @since 2.1 + * @deprecated this method has been replaced by {@code java.util.Objects.hashCode(Object)} in Java 7 and will be +removed in future releases + */ +public static int hashCode(final java.lang.Object obj) { + // hashCode(Object) retained for performance, as hash code is often critical + return /* NPEX_NULL_EXP */ + obj.hashCode(); +} + + /** + *

Gets the hash code for multiple objects.

+ * + *

This allows a hash code to be rapidly calculated for a number of objects. + * The hash code for a single object is the not same as {@link #hashCode(Object)}. + * The hash code for multiple objects is the same as that calculated by an + * {@code ArrayList} containing the specified objects.

+ * + *
+     * ObjectUtils.hashCodeMulti()                 = 1
+     * ObjectUtils.hashCodeMulti((Object[]) null)  = 1
+     * ObjectUtils.hashCodeMulti(a)                = 31 + a.hashCode()
+     * ObjectUtils.hashCodeMulti(a,b)              = (31 + a.hashCode()) * 31 + b.hashCode()
+     * ObjectUtils.hashCodeMulti(a,b,c)            = ((31 + a.hashCode()) * 31 + b.hashCode()) * 31 + c.hashCode()
+     * 
+ * + * @param objects the objects to obtain the hash code of, may be {@code null} + * @return the hash code of the objects, or zero if null + * @since 3.0 + * @deprecated this method has been replaced by {@code java.util.Objects.hash(Object...)} in Java 7 and will be + * removed in future releases. + */ + @Deprecated + public static int hashCodeMulti(final Object... objects) { + int hash = 1; + if (objects != null) { + for (final Object object : objects) { + final int tmpHash = ObjectUtils.hashCode(object); + hash = hash * 31 + tmpHash; + } + } + return hash; + } + + // Identity ToString + //----------------------------------------------------------------------- + /** + *

Gets the toString that would be produced by {@code Object} + * if a class did not override toString itself. {@code null} + * will return {@code null}.

+ * + *
+     * ObjectUtils.identityToString(null)         = null
+     * ObjectUtils.identityToString("")           = "java.lang.String@1e23"
+     * ObjectUtils.identityToString(Boolean.TRUE) = "java.lang.Boolean@7fa"
+     * 
+ * + * @param object the object to create a toString for, may be + * {@code null} + * @return the default toString text, or {@code null} if + * {@code null} passed in + */ + public static String identityToString(final Object object) { + if (object == null) { + return null; + } + final StringBuilder builder = new StringBuilder(); + identityToString(builder, object); + return builder.toString(); + } + + /** + *

Appends the toString that would be produced by {@code Object} + * if a class did not override toString itself. {@code null} + * will throw a NullPointerException for either of the two parameters.

+ * + *
+     * ObjectUtils.identityToString(appendable, "")            = appendable.append("java.lang.String@1e23"
+     * ObjectUtils.identityToString(appendable, Boolean.TRUE)  = appendable.append("java.lang.Boolean@7fa"
+     * ObjectUtils.identityToString(appendable, Boolean.TRUE)  = appendable.append("java.lang.Boolean@7fa")
+     * 
+ * + * @param appendable the appendable to append to + * @param object the object to create a toString for + * @throws IOException if an I/O error occurs + * @since 3.2 + */ + public static void identityToString(final Appendable appendable, final Object object) throws IOException { + if (object == null) { + throw new NullPointerException("Cannot get the toString of a null identity"); + } + appendable.append(object.getClass().getName()) + .append('@') + .append(Integer.toHexString(System.identityHashCode(object))); + } + + /** + *

Appends the toString that would be produced by {@code Object} + * if a class did not override toString itself. {@code null} + * will throw a NullPointerException for either of the two parameters.

+ * + *
+     * ObjectUtils.identityToString(builder, "")            = builder.append("java.lang.String@1e23"
+     * ObjectUtils.identityToString(builder, Boolean.TRUE)  = builder.append("java.lang.Boolean@7fa"
+     * ObjectUtils.identityToString(builder, Boolean.TRUE)  = builder.append("java.lang.Boolean@7fa")
+     * 
+ * + * @param builder the builder to append to + * @param object the object to create a toString for + * @since 3.2 + */ + public static void identityToString(final StrBuilder builder, final Object object) { + if (object == null) { + throw new NullPointerException("Cannot get the toString of a null identity"); + } + builder.append(object.getClass().getName()) + .append('@') + .append(Integer.toHexString(System.identityHashCode(object))); + } + + /** + *

Appends the toString that would be produced by {@code Object} + * if a class did not override toString itself. {@code null} + * will throw a NullPointerException for either of the two parameters.

+ * + *
+     * ObjectUtils.identityToString(buf, "")            = buf.append("java.lang.String@1e23"
+     * ObjectUtils.identityToString(buf, Boolean.TRUE)  = buf.append("java.lang.Boolean@7fa"
+     * ObjectUtils.identityToString(buf, Boolean.TRUE)  = buf.append("java.lang.Boolean@7fa")
+     * 
+ * + * @param buffer the buffer to append to + * @param object the object to create a toString for + * @since 2.4 + */ + public static void identityToString(final StringBuffer buffer, final Object object) { + if (object == null) { + throw new NullPointerException("Cannot get the toString of a null identity"); + } + buffer.append(object.getClass().getName()) + .append('@') + .append(Integer.toHexString(System.identityHashCode(object))); + } + + /** + *

Appends the toString that would be produced by {@code Object} + * if a class did not override toString itself. {@code null} + * will throw a NullPointerException for either of the two parameters.

+ * + *
+     * ObjectUtils.identityToString(builder, "")            = builder.append("java.lang.String@1e23"
+     * ObjectUtils.identityToString(builder, Boolean.TRUE)  = builder.append("java.lang.Boolean@7fa"
+     * ObjectUtils.identityToString(builder, Boolean.TRUE)  = builder.append("java.lang.Boolean@7fa")
+     * 
+ * + * @param builder the builder to append to + * @param object the object to create a toString for + * @since 3.2 + */ + public static void identityToString(final StringBuilder builder, final Object object) { + if (object == null) { + throw new NullPointerException("Cannot get the toString of a null identity"); + } + builder.append(object.getClass().getName()) + .append('@') + .append(Integer.toHexString(System.identityHashCode(object))); + } + + // ToString + //----------------------------------------------------------------------- + /** + *

Gets the {@code toString} of an {@code Object} returning + * an empty string ("") if {@code null} input.

+ * + *
+     * ObjectUtils.toString(null)         = ""
+     * ObjectUtils.toString("")           = ""
+     * ObjectUtils.toString("bat")        = "bat"
+     * ObjectUtils.toString(Boolean.TRUE) = "true"
+     * 
+ * + * @see StringUtils#defaultString(String) + * @see String#valueOf(Object) + * @param obj the Object to {@code toString}, may be null + * @return the passed in Object's toString, or {@code ""} if {@code null} input + * @since 2.0 + * @deprecated this method has been replaced by {@code java.util.Objects.toString(Object)} in Java 7 and will be + * removed in future releases. Note however that said method will return "null" for null references, while this + * method returns and empty String. To preserve behavior use {@code java.util.Objects.toString(myObject, "")} + */ + @Deprecated + public static String toString(final Object obj) { + return obj == null ? StringUtils.EMPTY : obj.toString(); + } + + /** + *

Gets the {@code toString} of an {@code Object} returning + * a specified text if {@code null} input.

+ * + *
+     * ObjectUtils.toString(null, null)           = null
+     * ObjectUtils.toString(null, "null")         = "null"
+     * ObjectUtils.toString("", "null")           = ""
+     * ObjectUtils.toString("bat", "null")        = "bat"
+     * ObjectUtils.toString(Boolean.TRUE, "null") = "true"
+     * 
+ * + * @see StringUtils#defaultString(String,String) + * @see String#valueOf(Object) + * @param obj the Object to {@code toString}, may be null + * @param nullStr the String to return if {@code null} input, may be null + * @return the passed in Object's toString, or {@code nullStr} if {@code null} input + * @since 2.0 + * @deprecated this method has been replaced by {@code java.util.Objects.toString(Object, String)} in Java 7 and + * will be removed in future releases. + */ + @Deprecated + public static String toString(final Object obj, final String nullStr) { + return obj == null ? nullStr : obj.toString(); + } + + // Comparable + //----------------------------------------------------------------------- + /** + *

Null safe comparison of Comparables.

+ * + * @param type of the values processed by this method + * @param values the set of comparable values, may be null + * @return + *
    + *
  • If any objects are non-null and unequal, the lesser object. + *
  • If all objects are non-null and equal, the first. + *
  • If any of the comparables are null, the lesser of the non-null objects. + *
  • If all the comparables are null, null is returned. + *
+ */ + public static > T min(final T... values) { + T result = null; + if (values != null) { + for (final T value : values) { + if (compare(value, result, true) < 0) { + result = value; + } + } + } + return result; + } + + /** + *

Null safe comparison of Comparables.

+ * + * @param type of the values processed by this method + * @param values the set of comparable values, may be null + * @return + *
    + *
  • If any objects are non-null and unequal, the greater object. + *
  • If all objects are non-null and equal, the first. + *
  • If any of the comparables are null, the greater of the non-null objects. + *
  • If all the comparables are null, null is returned. + *
+ */ + public static > T max(final T... values) { + T result = null; + if (values != null) { + for (final T value : values) { + if (compare(value, result, false) > 0) { + result = value; + } + } + } + return result; + } + + /** + *

Null safe comparison of Comparables. + * {@code null} is assumed to be less than a non-{@code null} value.

+ * + * @param type of the values processed by this method + * @param c1 the first comparable, may be null + * @param c2 the second comparable, may be null + * @return a negative value if c1 < c2, zero if c1 = c2 + * and a positive value if c1 > c2 + */ + public static > int compare(final T c1, final T c2) { + return compare(c1, c2, false); + } + + /** + *

Null safe comparison of Comparables.

+ * + * @param type of the values processed by this method + * @param c1 the first comparable, may be null + * @param c2 the second comparable, may be null + * @param nullGreater if true {@code null} is considered greater + * than a non-{@code null} value or if false {@code null} is + * considered less than a Non-{@code null} value + * @return a negative value if c1 < c2, zero if c1 = c2 + * and a positive value if c1 > c2 + * @see java.util.Comparator#compare(Object, Object) + */ + public static > int compare(final T c1, final T c2, final boolean nullGreater) { + if (c1 == c2) { + return 0; + } else if (c1 == null) { + return nullGreater ? 1 : -1; + } else if (c2 == null) { + return nullGreater ? -1 : 1; + } + return c1.compareTo(c2); + } + + /** + * Find the "best guess" middle value among comparables. If there is an even + * number of total values, the lower of the two middle values will be returned. + * @param type of values processed by this method + * @param items to compare + * @return T at middle position + * @throws NullPointerException if items is {@code null} + * @throws IllegalArgumentException if items is empty or contains {@code null} values + * @since 3.0.1 + */ + public static > T median(final T... items) { + Validate.notEmpty(items); + Validate.noNullElements(items); + final TreeSet sort = new TreeSet(); + Collections.addAll(sort, items); + @SuppressWarnings("unchecked") //we know all items added were T instances + final + T result = (T) sort.toArray()[(sort.size() - 1) / 2]; + return result; + } + + /** + * Find the "best guess" middle value among comparables. If there is an even + * number of total values, the lower of the two middle values will be returned. + * @param type of values processed by this method + * @param comparator to use for comparisons + * @param items to compare + * @return T at middle position + * @throws NullPointerException if items or comparator is {@code null} + * @throws IllegalArgumentException if items is empty or contains {@code null} values + * @since 3.0.1 + */ + public static T median(final Comparator comparator, final T... items) { + Validate.notEmpty(items, "null/empty items"); + Validate.noNullElements(items); + Validate.notNull(comparator, "null comparator"); + final TreeSet sort = new TreeSet(comparator); + Collections.addAll(sort, items); + @SuppressWarnings("unchecked") //we know all items added were T instances + final + T result = (T) sort.toArray()[(sort.size() - 1) / 2]; + return result; + } + + // Mode + //----------------------------------------------------------------------- + /** + * Find the most frequently occurring item. + * + * @param type of values processed by this method + * @param items to check + * @return most populous T, {@code null} if non-unique or no items supplied + * @since 3.0.1 + */ + public static T mode(final T... items) { + if (ArrayUtils.isNotEmpty(items)) { + final HashMap occurrences = new HashMap(items.length); + for (final T t : items) { + final MutableInt count = occurrences.get(t); + if (count == null) { + occurrences.put(t, new MutableInt(1)); + } else { + count.increment(); + } + } + T result = null; + int max = 0; + for (final Map.Entry e : occurrences.entrySet()) { + final int cmp = e.getValue().intValue(); + if (cmp == max) { + result = null; + } else if (cmp > max) { + max = cmp; + result = e.getKey(); + } + } + return result; + } + return null; + } + + // cloning + //----------------------------------------------------------------------- + /** + *

Clone an object.

+ * + * @param the type of the object + * @param obj the object to clone, null returns null + * @return the clone if the object implements {@link Cloneable} otherwise {@code null} + * @throws CloneFailedException if the object is cloneable and the clone operation fails + * @since 3.0 + */ + public static T clone(final T obj) { + if (obj instanceof Cloneable) { + final Object result; + if (obj.getClass().isArray()) { + final Class componentType = obj.getClass().getComponentType(); + if (!componentType.isPrimitive()) { + result = ((Object[]) obj).clone(); + } else { + int length = Array.getLength(obj); + result = Array.newInstance(componentType, length); + while (length-- > 0) { + Array.set(result, length, Array.get(obj, length)); + } + } + } else { + try { + final Method clone = obj.getClass().getMethod("clone"); + result = clone.invoke(obj); + } catch (final NoSuchMethodException e) { + throw new CloneFailedException("Cloneable type " + + obj.getClass().getName() + + " has no clone method", e); + } catch (final IllegalAccessException e) { + throw new CloneFailedException("Cannot clone Cloneable type " + + obj.getClass().getName(), e); + } catch (final InvocationTargetException e) { + throw new CloneFailedException("Exception cloning Cloneable type " + + obj.getClass().getName(), e.getCause()); + } + } + @SuppressWarnings("unchecked") // OK because input is of type T + final T checked = (T) result; + return checked; + } + + return null; + } + + /** + *

Clone an object if possible.

+ * + *

This method is similar to {@link #clone(Object)}, but will return the provided + * instance as the return value instead of {@code null} if the instance + * is not cloneable. This is more convenient if the caller uses different + * implementations (e.g. of a service) and some of the implementations do not allow concurrent + * processing or have state. In such cases the implementation can simply provide a proper + * clone implementation and the caller's code does not have to change.

+ * + * @param the type of the object + * @param obj the object to clone, null returns null + * @return the clone if the object implements {@link Cloneable} otherwise the object itself + * @throws CloneFailedException if the object is cloneable and the clone operation fails + * @since 3.0 + */ + public static T cloneIfPossible(final T obj) { + final T clone = clone(obj); + return clone == null ? obj : clone; + } + + // Null + //----------------------------------------------------------------------- + /** + *

Class used as a null placeholder where {@code null} + * has another meaning.

+ * + *

For example, in a {@code HashMap} the + * {@link java.util.HashMap#get(java.lang.Object)} method returns + * {@code null} if the {@code Map} contains {@code null} or if there is + * no matching key. The {@code Null} placeholder can be used to distinguish + * between these two cases.

+ * + *

Another example is {@code Hashtable}, where {@code null} + * cannot be stored.

+ */ + public static class Null implements Serializable { + /** + * Required for serialization support. Declare serialization compatibility with Commons Lang 1.0 + * + * @see java.io.Serializable + */ + private static final long serialVersionUID = 7092611880189329093L; + + /** + * Restricted constructor - singleton. + */ + Null() { + super(); + } + + /** + *

Ensure singleton.

+ * + * @return the singleton value + */ + private Object readResolve() { + return ObjectUtils.NULL; + } + } + + + // Constants (LANG-816): + /* + These methods ensure constants are not inlined by javac. + For example, typically a developer might declare a constant like so: + + public final static int MAGIC_NUMBER = 5; + + Should a different jar file refer to this, and the MAGIC_NUMBER + is changed a later date (e.g., MAGIC_NUMBER = 6), the different jar + file will need to recompile itself. This is because javac + typically inlines the primitive or String constant directly into + the bytecode, and removes the reference to the MAGIC_NUMBER field. + + To help the other jar (so that it does not need to recompile + when constants are changed) the original developer can declare + their constant using one of the CONST() utility methods, instead: + + public final static int MAGIC_NUMBER = CONST(5); + */ + + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static boolean MAGIC_FLAG = ObjectUtils.CONST(true);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the boolean value to return + * @return the boolean v, unchanged + * @since 3.2 + */ + public static boolean CONST(final boolean v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static byte MAGIC_BYTE = ObjectUtils.CONST((byte) 127);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the byte value to return + * @return the byte v, unchanged + * @since 3.2 + */ + public static byte CONST(final byte v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static byte MAGIC_BYTE = ObjectUtils.CONST_BYTE(127);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the byte literal (as an int) value to return + * @throws IllegalArgumentException if the value passed to v + * is larger than a byte, that is, smaller than -128 or + * larger than 127. + * @return the byte v, unchanged + * @since 3.2 + */ + public static byte CONST_BYTE(final int v) throws IllegalArgumentException { + if (v < Byte.MIN_VALUE || v > Byte.MAX_VALUE) { + throw new IllegalArgumentException("Supplied value must be a valid byte literal between -128 and 127: [" + v + "]"); + } + return (byte) v; + } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static char MAGIC_CHAR = ObjectUtils.CONST('a');
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the char value to return + * @return the char v, unchanged + * @since 3.2 + */ + public static char CONST(final char v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static short MAGIC_SHORT = ObjectUtils.CONST((short) 123);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the short value to return + * @return the short v, unchanged + * @since 3.2 + */ + public static short CONST(final short v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static short MAGIC_SHORT = ObjectUtils.CONST_SHORT(127);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the short literal (as an int) value to return + * @throws IllegalArgumentException if the value passed to v + * is larger than a short, that is, smaller than -32768 or + * larger than 32767. + * @return the byte v, unchanged + * @since 3.2 + */ + public static short CONST_SHORT(final int v) throws IllegalArgumentException { + if (v < Short.MIN_VALUE || v > Short.MAX_VALUE) { + throw new IllegalArgumentException("Supplied value must be a valid byte literal between -32768 and 32767: [" + v + "]"); + } + return (short) v; + } + + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static int MAGIC_INT = ObjectUtils.CONST(123);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the int value to return + * @return the int v, unchanged + * @since 3.2 + */ + public static int CONST(final int v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static long MAGIC_LONG = ObjectUtils.CONST(123L);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the long value to return + * @return the long v, unchanged + * @since 3.2 + */ + public static long CONST(final long v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static float MAGIC_FLOAT = ObjectUtils.CONST(1.0f);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the float value to return + * @return the float v, unchanged + * @since 3.2 + */ + public static float CONST(final float v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static double MAGIC_DOUBLE = ObjectUtils.CONST(1.0);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the double value to return + * @return the double v, unchanged + * @since 3.2 + */ + public static double CONST(final double v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static String MAGIC_STRING = ObjectUtils.CONST("abc");
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param the Object type + * @param v the genericized Object value to return (typically a String). + * @return the genericized Object v, unchanged (typically a String). + * @since 3.2 + */ + public static T CONST(final T v) { return v; } + +} diff --git a/Java/commons-lang-ObjectUtils_272/metadata.json b/Java/commons-lang-ObjectUtils_272/metadata.json new file mode 100644 index 000000000..f5696e70e --- /dev/null +++ b/Java/commons-lang-ObjectUtils_272/metadata.json @@ -0,0 +1,21 @@ +{ + "language": "java", + "id": "commons-lang-ObjectUtils_272", + "buggyPath": ".", + "referencePath": null, + "buildCommand": "mvn package -V -B -Denforcer.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true -Drat.skip=true -Dlicense.skip=true -Dfindbugs.skip=true -Dgpg.skip=true -Dskip.npm=true -Dskip.gulp=true -Dskip.bower=true -Drat.numUnapprovedLicenses=100 -DskipTests=true -DskipITs=true -Dtest=None -DfailIfNoTests=false", + "testCommand": "mvn test -V -B -Denforcer.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true -Drat.skip=true -Dlicense.skip=true -Dfindbugs.skip=true -Dgpg.skip=true -Dskip.npm=true -Dskip.gulp=true -Dskip.bower=true -Drat.numUnapprovedLicenses=100", + "categories": [ + "safety", + "npe" + ], + "npe": { + "filepath": "src/main/java/org/apache/commons/lang3/ObjectUtils.java", + "line": 289, + "npe_method": "hashCode", + "deref_field": "obj", + "npe_class": "ObjectUtils", + "repo": "commons-lang", + "bug_id": "ObjectUtils_272" + } +} diff --git a/Java/commons-lang-ObjectUtils_272/npe.json b/Java/commons-lang-ObjectUtils_272/npe.json new file mode 100644 index 000000000..2f433b8f7 --- /dev/null +++ b/Java/commons-lang-ObjectUtils_272/npe.json @@ -0,0 +1,7 @@ +{ + "filepath": "src/main/java/org/apache/commons/lang3/ObjectUtils.java", + "line": 289, + "npe_method": "hashCode", + "deref_field": "obj", + "npe_class": "ObjectUtils" +} \ No newline at end of file diff --git a/Java/commons-lang-ObjectUtils_300/Dockerfile b/Java/commons-lang-ObjectUtils_300/Dockerfile new file mode 100644 index 000000000..7b7fbe349 --- /dev/null +++ b/Java/commons-lang-ObjectUtils_300/Dockerfile @@ -0,0 +1,18 @@ +FROM ghcr.io/kupl/starlab-benchmarks/java-base:commons-lang + +ENV TZ=Asia/Seoul + +COPY ./metadata.json . +COPY ./npe.json . +COPY ./buggy.java /tmp/buggy.java +RUN export BUGGY_PATH=$(cat metadata.json | jq -r ".npe.filepath") \ + && export BUGGY_LINE=$(cat metadata.json | jq -r ".npe.line") \ + && export BUGGY_MTHD=$(cat metadata.json | jq -r ".npe.npe_method") \ + && mv /tmp/buggy.java $BUGGY_PATH \ + && echo "[{\"filepath\": \"$BUGGY_PATH\", \"line\": $BUGGY_LINE, \"method_name\": \"$BUGGY_MTHD\"}]" | jq . > traces.json + +RUN git init . && git add -A + +RUN $(cat metadata.json | jq -r ".buildCommand") + +RUN $(cat metadata.json | jq -r ".testCommand"); if [ $? -eq 0 ]; then exit 1; fi diff --git a/Java/commons-lang-ObjectUtils_300/buggy.java b/Java/commons-lang-ObjectUtils_300/buggy.java new file mode 100644 index 000000000..35ea8f574 --- /dev/null +++ b/Java/commons-lang-ObjectUtils_300/buggy.java @@ -0,0 +1,1040 @@ +/* + * 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.Serializable; +import java.lang.reflect.Array; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.Map; +import java.util.TreeSet; + +import org.apache.commons.lang3.exception.CloneFailedException; +import org.apache.commons.lang3.mutable.MutableInt; +import org.apache.commons.lang3.text.StrBuilder; + +/** + *

Operations on {@code Object}.

+ * + *

This class tries to handle {@code null} input gracefully. + * An exception will generally not be thrown for a {@code null} input. + * Each method documents its behaviour in more detail.

+ * + *

#ThreadSafe#

+ * @since 1.0 + */ +//@Immutable +public class ObjectUtils { + + /** + *

Singleton used as a {@code null} placeholder where + * {@code null} has another meaning.

+ * + *

For example, in a {@code HashMap} the + * {@link java.util.HashMap#get(java.lang.Object)} method returns + * {@code null} if the {@code Map} contains {@code null} or if there + * is no matching key. The {@code Null} placeholder can be used to + * distinguish between these two cases.

+ * + *

Another example is {@code Hashtable}, where {@code null} + * cannot be stored.

+ * + *

This instance is Serializable.

+ */ + public static final Null NULL = new Null(); + + /** + *

{@code ObjectUtils} instances should NOT be constructed in + * standard programming. Instead, the static methods on the class should + * be used, such as {@code ObjectUtils.defaultIfNull("a","b");}.

+ * + *

This constructor is public to permit tools that require a JavaBean + * instance to operate.

+ */ + public ObjectUtils() { + super(); + } + + // Defaulting + //----------------------------------------------------------------------- + /** + *

Returns a default value if the object passed is {@code null}.

+ * + *
+     * ObjectUtils.defaultIfNull(null, null)      = null
+     * ObjectUtils.defaultIfNull(null, "")        = ""
+     * ObjectUtils.defaultIfNull(null, "zz")      = "zz"
+     * ObjectUtils.defaultIfNull("abc", *)        = "abc"
+     * ObjectUtils.defaultIfNull(Boolean.TRUE, *) = Boolean.TRUE
+     * 
+ * + * @param the type of the object + * @param object the {@code Object} to test, may be {@code null} + * @param defaultValue the default value to return, may be {@code null} + * @return {@code object} if it is not {@code null}, defaultValue otherwise + */ + public static T defaultIfNull(final T object, final T defaultValue) { + return object != null ? object : defaultValue; + } + + /** + *

Returns the first value in the array which is not {@code null}. + * If all the values are {@code null} or the array is {@code null} + * or empty then {@code null} is returned.

+ * + *
+     * ObjectUtils.firstNonNull(null, null)      = null
+     * ObjectUtils.firstNonNull(null, "")        = ""
+     * ObjectUtils.firstNonNull(null, null, "")  = ""
+     * ObjectUtils.firstNonNull(null, "zz")      = "zz"
+     * ObjectUtils.firstNonNull("abc", *)        = "abc"
+     * ObjectUtils.firstNonNull(null, "xyz", *)  = "xyz"
+     * ObjectUtils.firstNonNull(Boolean.TRUE, *) = Boolean.TRUE
+     * ObjectUtils.firstNonNull()                = null
+     * 
+ * + * @param the component type of the array + * @param values the values to test, may be {@code null} or empty + * @return the first value from {@code values} which is not {@code null}, + * or {@code null} if there are no non-null values + * @since 3.0 + */ + public static T firstNonNull(final T... values) { + if (values != null) { + for (final T val : values) { + if (val != null) { + return val; + } + } + } + return null; + } + + /** + * Checks if any value in the given array is not {@code null}. + * + *

+ * If all the values are {@code null} or the array is {@code null} + * or empty then {@code false} is returned. Otherwise {@code true} is returned. + *

+ * + *
+     * ObjectUtils.anyNotNull(*)                = true
+     * ObjectUtils.anyNotNull(*, null)          = true
+     * ObjectUtils.anyNotNull(null, *)          = true
+     * ObjectUtils.anyNotNull(null, null, *, *) = true
+     * ObjectUtils.anyNotNull(null)             = false
+     * ObjectUtils.anyNotNull(null, null)       = false
+     * 
+ * + * @param values the values to test, may be {@code null} or empty + * @return {@code true} if there is at least one non-null value in the array, + * {@code false} if all values in the array are {@code null}s. + * If the array is {@code null} or empty {@code false} is also returned. + * @since 3.5 + */ + public static boolean anyNotNull(final Object... values) { + return firstNonNull(values) != null; + } + + /** + * Checks if all values in the array are not {@code nulls}. + * + *

+ * If any value is {@code null} or the array is {@code null} then + * {@code false} is returned. If all elements in array are not + * {@code null} or the array is empty (contains no elements) {@code true} + * is returned. + *

+ * + *
+     * ObjectUtils.allNotNull(*)             = true
+     * ObjectUtils.allNotNull(*, *)          = true
+     * ObjectUtils.allNotNull(null)          = false
+     * ObjectUtils.allNotNull(null, null)    = false
+     * ObjectUtils.allNotNull(null, *)       = false
+     * ObjectUtils.allNotNull(*, null)       = false
+     * ObjectUtils.allNotNull(*, *, null, *) = false
+     * 
+ * + * @param values the values to test, may be {@code null} or empty + * @return {@code false} if there is at least one {@code null} value in the array or the array is {@code null}, + * {@code true} if all values in the array are not {@code null}s or array contains no elements. + * @since 3.5 + */ + public static boolean allNotNull(final Object... values) { + if (values == null) { + return false; + } + + for (final Object val : values) { + if (val == null) { + return false; + } + } + + return true; + } + + // Null-safe equals/hashCode + //----------------------------------------------------------------------- + /** + *

Compares two objects for equality, where either one or both + * objects may be {@code null}.

+ * + *
+     * ObjectUtils.equals(null, null)                  = true
+     * ObjectUtils.equals(null, "")                    = false
+     * ObjectUtils.equals("", null)                    = false
+     * ObjectUtils.equals("", "")                      = true
+     * ObjectUtils.equals(Boolean.TRUE, null)          = false
+     * ObjectUtils.equals(Boolean.TRUE, "true")        = false
+     * ObjectUtils.equals(Boolean.TRUE, Boolean.TRUE)  = true
+     * ObjectUtils.equals(Boolean.TRUE, Boolean.FALSE) = false
+     * 
+ * + * @param object1 the first object, may be {@code null} + * @param object2 the second object, may be {@code null} + * @return {@code true} if the values of both objects are the same + * @deprecated this method has been replaced by {@code java.util.Objects.equals(Object, Object)} in Java 7 and will + * be removed from future releases. + */ + @Deprecated + public static boolean equals(final Object object1, final Object object2) { + if (object1 == object2) { + return true; + } + if (object1 == null || object2 == null) { + return false; + } + return object1.equals(object2); + } + + /** + *

Compares two objects for inequality, where either one or both + * objects may be {@code null}.

+ * + *
+     * ObjectUtils.notEqual(null, null)                  = false
+     * ObjectUtils.notEqual(null, "")                    = true
+     * ObjectUtils.notEqual("", null)                    = true
+     * ObjectUtils.notEqual("", "")                      = false
+     * ObjectUtils.notEqual(Boolean.TRUE, null)          = true
+     * ObjectUtils.notEqual(Boolean.TRUE, "true")        = true
+     * ObjectUtils.notEqual(Boolean.TRUE, Boolean.TRUE)  = false
+     * ObjectUtils.notEqual(Boolean.TRUE, Boolean.FALSE) = true
+     * 
+ * + * @param object1 the first object, may be {@code null} + * @param object2 the second object, may be {@code null} + * @return {@code false} if the values of both objects are the same + */ + public static boolean notEqual(final Object object1, final Object object2) { + return ObjectUtils.equals(object1, object2) == false; + } + + /** + *

Gets the hash code of an object returning zero when the + * object is {@code null}.

+ * + *
+     * ObjectUtils.hashCode(null)   = 0
+     * ObjectUtils.hashCode(obj)    = obj.hashCode()
+     * 
+ * + * @param obj the object to obtain the hash code of, may be {@code null} + * @return the hash code of the object, or zero if null + * @since 2.1 + * @deprecated this method has been replaced by {@code java.util.Objects.hashCode(Object)} in Java 7 and will be + * removed in future releases + */ + @Deprecated + public static int hashCode(final Object obj) { + // hashCode(Object) retained for performance, as hash code is often critical + return obj == null ? 0 : obj.hashCode(); + } + + /** + *

Gets the hash code for multiple objects.

+ * + *

This allows a hash code to be rapidly calculated for a number of objects. + * The hash code for a single object is the not same as {@link #hashCode(Object)}. + * The hash code for multiple objects is the same as that calculated by an + * {@code ArrayList} containing the specified objects.

+ * + *
+     * ObjectUtils.hashCodeMulti()                 = 1
+     * ObjectUtils.hashCodeMulti((Object[]) null)  = 1
+     * ObjectUtils.hashCodeMulti(a)                = 31 + a.hashCode()
+     * ObjectUtils.hashCodeMulti(a,b)              = (31 + a.hashCode()) * 31 + b.hashCode()
+     * ObjectUtils.hashCodeMulti(a,b,c)            = ((31 + a.hashCode()) * 31 + b.hashCode()) * 31 + c.hashCode()
+     * 
+ * + * @param objects the objects to obtain the hash code of, may be {@code null} + * @return the hash code of the objects, or zero if null + * @since 3.0 + * @deprecated this method has been replaced by {@code java.util.Objects.hash(Object...)} in Java 7 and will be + * removed in future releases. + */ + @Deprecated +/** + *

Gets the hash code for multiple objects.

+ * + *

This allows a hash code to be rapidly calculated for a number of objects. + * The hash code for a single object is the not same as {@link #hashCode(Object)}. + * The hash code for multiple objects is the same as that calculated by an + * {@code ArrayList} containing the specified objects.

+ * + *
+ * ObjectUtils.hashCodeMulti()                 = 1
+ * ObjectUtils.hashCodeMulti((Object[]) null)  = 1
+ * ObjectUtils.hashCodeMulti(a)                = 31 + a.hashCode()
+ * ObjectUtils.hashCodeMulti(a,b)              = (31 + a.hashCode()) * 31 + b.hashCode()
+ * ObjectUtils.hashCodeMulti(a,b,c)            = ((31 + a.hashCode()) * 31 + b.hashCode()) * 31 + c.hashCode()
+ * 
+ * + * @param objects + * the objects to obtain the hash code of, may be {@code null} + * @return the hash code of the objects, or zero if null + * @since 3.0 + * @deprecated this method has been replaced by {@code java.util.Objects.hash(Object...)} in Java 7 and will be +removed in future releases. + */ +public static int hashCodeMulti(final java.lang.Object... objects) { + int hash = 1; + { + for (final java.lang.Object object : /* NPEX_NULL_EXP */ + objects) { + final int tmpHash = org.apache.commons.lang3.ObjectUtils.hashCode(object); + hash = (hash * 31) + tmpHash; + } + } + return hash; +} + + // Identity ToString + //----------------------------------------------------------------------- + /** + *

Gets the toString that would be produced by {@code Object} + * if a class did not override toString itself. {@code null} + * will return {@code null}.

+ * + *
+     * ObjectUtils.identityToString(null)         = null
+     * ObjectUtils.identityToString("")           = "java.lang.String@1e23"
+     * ObjectUtils.identityToString(Boolean.TRUE) = "java.lang.Boolean@7fa"
+     * 
+ * + * @param object the object to create a toString for, may be + * {@code null} + * @return the default toString text, or {@code null} if + * {@code null} passed in + */ + public static String identityToString(final Object object) { + if (object == null) { + return null; + } + final StringBuilder builder = new StringBuilder(); + identityToString(builder, object); + return builder.toString(); + } + + /** + *

Appends the toString that would be produced by {@code Object} + * if a class did not override toString itself. {@code null} + * will throw a NullPointerException for either of the two parameters.

+ * + *
+     * ObjectUtils.identityToString(appendable, "")            = appendable.append("java.lang.String@1e23"
+     * ObjectUtils.identityToString(appendable, Boolean.TRUE)  = appendable.append("java.lang.Boolean@7fa"
+     * ObjectUtils.identityToString(appendable, Boolean.TRUE)  = appendable.append("java.lang.Boolean@7fa")
+     * 
+ * + * @param appendable the appendable to append to + * @param object the object to create a toString for + * @throws IOException if an I/O error occurs + * @since 3.2 + */ + public static void identityToString(final Appendable appendable, final Object object) throws IOException { + if (object == null) { + throw new NullPointerException("Cannot get the toString of a null identity"); + } + appendable.append(object.getClass().getName()) + .append('@') + .append(Integer.toHexString(System.identityHashCode(object))); + } + + /** + *

Appends the toString that would be produced by {@code Object} + * if a class did not override toString itself. {@code null} + * will throw a NullPointerException for either of the two parameters.

+ * + *
+     * ObjectUtils.identityToString(builder, "")            = builder.append("java.lang.String@1e23"
+     * ObjectUtils.identityToString(builder, Boolean.TRUE)  = builder.append("java.lang.Boolean@7fa"
+     * ObjectUtils.identityToString(builder, Boolean.TRUE)  = builder.append("java.lang.Boolean@7fa")
+     * 
+ * + * @param builder the builder to append to + * @param object the object to create a toString for + * @since 3.2 + */ + public static void identityToString(final StrBuilder builder, final Object object) { + if (object == null) { + throw new NullPointerException("Cannot get the toString of a null identity"); + } + builder.append(object.getClass().getName()) + .append('@') + .append(Integer.toHexString(System.identityHashCode(object))); + } + + /** + *

Appends the toString that would be produced by {@code Object} + * if a class did not override toString itself. {@code null} + * will throw a NullPointerException for either of the two parameters.

+ * + *
+     * ObjectUtils.identityToString(buf, "")            = buf.append("java.lang.String@1e23"
+     * ObjectUtils.identityToString(buf, Boolean.TRUE)  = buf.append("java.lang.Boolean@7fa"
+     * ObjectUtils.identityToString(buf, Boolean.TRUE)  = buf.append("java.lang.Boolean@7fa")
+     * 
+ * + * @param buffer the buffer to append to + * @param object the object to create a toString for + * @since 2.4 + */ + public static void identityToString(final StringBuffer buffer, final Object object) { + if (object == null) { + throw new NullPointerException("Cannot get the toString of a null identity"); + } + buffer.append(object.getClass().getName()) + .append('@') + .append(Integer.toHexString(System.identityHashCode(object))); + } + + /** + *

Appends the toString that would be produced by {@code Object} + * if a class did not override toString itself. {@code null} + * will throw a NullPointerException for either of the two parameters.

+ * + *
+     * ObjectUtils.identityToString(builder, "")            = builder.append("java.lang.String@1e23"
+     * ObjectUtils.identityToString(builder, Boolean.TRUE)  = builder.append("java.lang.Boolean@7fa"
+     * ObjectUtils.identityToString(builder, Boolean.TRUE)  = builder.append("java.lang.Boolean@7fa")
+     * 
+ * + * @param builder the builder to append to + * @param object the object to create a toString for + * @since 3.2 + */ + public static void identityToString(final StringBuilder builder, final Object object) { + if (object == null) { + throw new NullPointerException("Cannot get the toString of a null identity"); + } + builder.append(object.getClass().getName()) + .append('@') + .append(Integer.toHexString(System.identityHashCode(object))); + } + + // ToString + //----------------------------------------------------------------------- + /** + *

Gets the {@code toString} of an {@code Object} returning + * an empty string ("") if {@code null} input.

+ * + *
+     * ObjectUtils.toString(null)         = ""
+     * ObjectUtils.toString("")           = ""
+     * ObjectUtils.toString("bat")        = "bat"
+     * ObjectUtils.toString(Boolean.TRUE) = "true"
+     * 
+ * + * @see StringUtils#defaultString(String) + * @see String#valueOf(Object) + * @param obj the Object to {@code toString}, may be null + * @return the passed in Object's toString, or {@code ""} if {@code null} input + * @since 2.0 + * @deprecated this method has been replaced by {@code java.util.Objects.toString(Object)} in Java 7 and will be + * removed in future releases. Note however that said method will return "null" for null references, while this + * method returns and empty String. To preserve behavior use {@code java.util.Objects.toString(myObject, "")} + */ + @Deprecated + public static String toString(final Object obj) { + return obj == null ? StringUtils.EMPTY : obj.toString(); + } + + /** + *

Gets the {@code toString} of an {@code Object} returning + * a specified text if {@code null} input.

+ * + *
+     * ObjectUtils.toString(null, null)           = null
+     * ObjectUtils.toString(null, "null")         = "null"
+     * ObjectUtils.toString("", "null")           = ""
+     * ObjectUtils.toString("bat", "null")        = "bat"
+     * ObjectUtils.toString(Boolean.TRUE, "null") = "true"
+     * 
+ * + * @see StringUtils#defaultString(String,String) + * @see String#valueOf(Object) + * @param obj the Object to {@code toString}, may be null + * @param nullStr the String to return if {@code null} input, may be null + * @return the passed in Object's toString, or {@code nullStr} if {@code null} input + * @since 2.0 + * @deprecated this method has been replaced by {@code java.util.Objects.toString(Object, String)} in Java 7 and + * will be removed in future releases. + */ + @Deprecated + public static String toString(final Object obj, final String nullStr) { + return obj == null ? nullStr : obj.toString(); + } + + // Comparable + //----------------------------------------------------------------------- + /** + *

Null safe comparison of Comparables.

+ * + * @param type of the values processed by this method + * @param values the set of comparable values, may be null + * @return + *
    + *
  • If any objects are non-null and unequal, the lesser object. + *
  • If all objects are non-null and equal, the first. + *
  • If any of the comparables are null, the lesser of the non-null objects. + *
  • If all the comparables are null, null is returned. + *
+ */ + public static > T min(final T... values) { + T result = null; + if (values != null) { + for (final T value : values) { + if (compare(value, result, true) < 0) { + result = value; + } + } + } + return result; + } + + /** + *

Null safe comparison of Comparables.

+ * + * @param type of the values processed by this method + * @param values the set of comparable values, may be null + * @return + *
    + *
  • If any objects are non-null and unequal, the greater object. + *
  • If all objects are non-null and equal, the first. + *
  • If any of the comparables are null, the greater of the non-null objects. + *
  • If all the comparables are null, null is returned. + *
+ */ + public static > T max(final T... values) { + T result = null; + if (values != null) { + for (final T value : values) { + if (compare(value, result, false) > 0) { + result = value; + } + } + } + return result; + } + + /** + *

Null safe comparison of Comparables. + * {@code null} is assumed to be less than a non-{@code null} value.

+ * + * @param type of the values processed by this method + * @param c1 the first comparable, may be null + * @param c2 the second comparable, may be null + * @return a negative value if c1 < c2, zero if c1 = c2 + * and a positive value if c1 > c2 + */ + public static > int compare(final T c1, final T c2) { + return compare(c1, c2, false); + } + + /** + *

Null safe comparison of Comparables.

+ * + * @param type of the values processed by this method + * @param c1 the first comparable, may be null + * @param c2 the second comparable, may be null + * @param nullGreater if true {@code null} is considered greater + * than a non-{@code null} value or if false {@code null} is + * considered less than a Non-{@code null} value + * @return a negative value if c1 < c2, zero if c1 = c2 + * and a positive value if c1 > c2 + * @see java.util.Comparator#compare(Object, Object) + */ + public static > int compare(final T c1, final T c2, final boolean nullGreater) { + if (c1 == c2) { + return 0; + } else if (c1 == null) { + return nullGreater ? 1 : -1; + } else if (c2 == null) { + return nullGreater ? -1 : 1; + } + return c1.compareTo(c2); + } + + /** + * Find the "best guess" middle value among comparables. If there is an even + * number of total values, the lower of the two middle values will be returned. + * @param type of values processed by this method + * @param items to compare + * @return T at middle position + * @throws NullPointerException if items is {@code null} + * @throws IllegalArgumentException if items is empty or contains {@code null} values + * @since 3.0.1 + */ + public static > T median(final T... items) { + Validate.notEmpty(items); + Validate.noNullElements(items); + final TreeSet sort = new TreeSet(); + Collections.addAll(sort, items); + @SuppressWarnings("unchecked") //we know all items added were T instances + final + T result = (T) sort.toArray()[(sort.size() - 1) / 2]; + return result; + } + + /** + * Find the "best guess" middle value among comparables. If there is an even + * number of total values, the lower of the two middle values will be returned. + * @param type of values processed by this method + * @param comparator to use for comparisons + * @param items to compare + * @return T at middle position + * @throws NullPointerException if items or comparator is {@code null} + * @throws IllegalArgumentException if items is empty or contains {@code null} values + * @since 3.0.1 + */ + public static T median(final Comparator comparator, final T... items) { + Validate.notEmpty(items, "null/empty items"); + Validate.noNullElements(items); + Validate.notNull(comparator, "null comparator"); + final TreeSet sort = new TreeSet(comparator); + Collections.addAll(sort, items); + @SuppressWarnings("unchecked") //we know all items added were T instances + final + T result = (T) sort.toArray()[(sort.size() - 1) / 2]; + return result; + } + + // Mode + //----------------------------------------------------------------------- + /** + * Find the most frequently occurring item. + * + * @param type of values processed by this method + * @param items to check + * @return most populous T, {@code null} if non-unique or no items supplied + * @since 3.0.1 + */ + public static T mode(final T... items) { + if (ArrayUtils.isNotEmpty(items)) { + final HashMap occurrences = new HashMap(items.length); + for (final T t : items) { + final MutableInt count = occurrences.get(t); + if (count == null) { + occurrences.put(t, new MutableInt(1)); + } else { + count.increment(); + } + } + T result = null; + int max = 0; + for (final Map.Entry e : occurrences.entrySet()) { + final int cmp = e.getValue().intValue(); + if (cmp == max) { + result = null; + } else if (cmp > max) { + max = cmp; + result = e.getKey(); + } + } + return result; + } + return null; + } + + // cloning + //----------------------------------------------------------------------- + /** + *

Clone an object.

+ * + * @param the type of the object + * @param obj the object to clone, null returns null + * @return the clone if the object implements {@link Cloneable} otherwise {@code null} + * @throws CloneFailedException if the object is cloneable and the clone operation fails + * @since 3.0 + */ + public static T clone(final T obj) { + if (obj instanceof Cloneable) { + final Object result; + if (obj.getClass().isArray()) { + final Class componentType = obj.getClass().getComponentType(); + if (!componentType.isPrimitive()) { + result = ((Object[]) obj).clone(); + } else { + int length = Array.getLength(obj); + result = Array.newInstance(componentType, length); + while (length-- > 0) { + Array.set(result, length, Array.get(obj, length)); + } + } + } else { + try { + final Method clone = obj.getClass().getMethod("clone"); + result = clone.invoke(obj); + } catch (final NoSuchMethodException e) { + throw new CloneFailedException("Cloneable type " + + obj.getClass().getName() + + " has no clone method", e); + } catch (final IllegalAccessException e) { + throw new CloneFailedException("Cannot clone Cloneable type " + + obj.getClass().getName(), e); + } catch (final InvocationTargetException e) { + throw new CloneFailedException("Exception cloning Cloneable type " + + obj.getClass().getName(), e.getCause()); + } + } + @SuppressWarnings("unchecked") // OK because input is of type T + final T checked = (T) result; + return checked; + } + + return null; + } + + /** + *

Clone an object if possible.

+ * + *

This method is similar to {@link #clone(Object)}, but will return the provided + * instance as the return value instead of {@code null} if the instance + * is not cloneable. This is more convenient if the caller uses different + * implementations (e.g. of a service) and some of the implementations do not allow concurrent + * processing or have state. In such cases the implementation can simply provide a proper + * clone implementation and the caller's code does not have to change.

+ * + * @param the type of the object + * @param obj the object to clone, null returns null + * @return the clone if the object implements {@link Cloneable} otherwise the object itself + * @throws CloneFailedException if the object is cloneable and the clone operation fails + * @since 3.0 + */ + public static T cloneIfPossible(final T obj) { + final T clone = clone(obj); + return clone == null ? obj : clone; + } + + // Null + //----------------------------------------------------------------------- + /** + *

Class used as a null placeholder where {@code null} + * has another meaning.

+ * + *

For example, in a {@code HashMap} the + * {@link java.util.HashMap#get(java.lang.Object)} method returns + * {@code null} if the {@code Map} contains {@code null} or if there is + * no matching key. The {@code Null} placeholder can be used to distinguish + * between these two cases.

+ * + *

Another example is {@code Hashtable}, where {@code null} + * cannot be stored.

+ */ + public static class Null implements Serializable { + /** + * Required for serialization support. Declare serialization compatibility with Commons Lang 1.0 + * + * @see java.io.Serializable + */ + private static final long serialVersionUID = 7092611880189329093L; + + /** + * Restricted constructor - singleton. + */ + Null() { + super(); + } + + /** + *

Ensure singleton.

+ * + * @return the singleton value + */ + private Object readResolve() { + return ObjectUtils.NULL; + } + } + + + // Constants (LANG-816): + /* + These methods ensure constants are not inlined by javac. + For example, typically a developer might declare a constant like so: + + public final static int MAGIC_NUMBER = 5; + + Should a different jar file refer to this, and the MAGIC_NUMBER + is changed a later date (e.g., MAGIC_NUMBER = 6), the different jar + file will need to recompile itself. This is because javac + typically inlines the primitive or String constant directly into + the bytecode, and removes the reference to the MAGIC_NUMBER field. + + To help the other jar (so that it does not need to recompile + when constants are changed) the original developer can declare + their constant using one of the CONST() utility methods, instead: + + public final static int MAGIC_NUMBER = CONST(5); + */ + + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static boolean MAGIC_FLAG = ObjectUtils.CONST(true);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the boolean value to return + * @return the boolean v, unchanged + * @since 3.2 + */ + public static boolean CONST(final boolean v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static byte MAGIC_BYTE = ObjectUtils.CONST((byte) 127);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the byte value to return + * @return the byte v, unchanged + * @since 3.2 + */ + public static byte CONST(final byte v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static byte MAGIC_BYTE = ObjectUtils.CONST_BYTE(127);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the byte literal (as an int) value to return + * @throws IllegalArgumentException if the value passed to v + * is larger than a byte, that is, smaller than -128 or + * larger than 127. + * @return the byte v, unchanged + * @since 3.2 + */ + public static byte CONST_BYTE(final int v) throws IllegalArgumentException { + if (v < Byte.MIN_VALUE || v > Byte.MAX_VALUE) { + throw new IllegalArgumentException("Supplied value must be a valid byte literal between -128 and 127: [" + v + "]"); + } + return (byte) v; + } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static char MAGIC_CHAR = ObjectUtils.CONST('a');
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the char value to return + * @return the char v, unchanged + * @since 3.2 + */ + public static char CONST(final char v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static short MAGIC_SHORT = ObjectUtils.CONST((short) 123);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the short value to return + * @return the short v, unchanged + * @since 3.2 + */ + public static short CONST(final short v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static short MAGIC_SHORT = ObjectUtils.CONST_SHORT(127);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the short literal (as an int) value to return + * @throws IllegalArgumentException if the value passed to v + * is larger than a short, that is, smaller than -32768 or + * larger than 32767. + * @return the byte v, unchanged + * @since 3.2 + */ + public static short CONST_SHORT(final int v) throws IllegalArgumentException { + if (v < Short.MIN_VALUE || v > Short.MAX_VALUE) { + throw new IllegalArgumentException("Supplied value must be a valid byte literal between -32768 and 32767: [" + v + "]"); + } + return (short) v; + } + + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static int MAGIC_INT = ObjectUtils.CONST(123);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the int value to return + * @return the int v, unchanged + * @since 3.2 + */ + public static int CONST(final int v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static long MAGIC_LONG = ObjectUtils.CONST(123L);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the long value to return + * @return the long v, unchanged + * @since 3.2 + */ + public static long CONST(final long v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static float MAGIC_FLOAT = ObjectUtils.CONST(1.0f);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the float value to return + * @return the float v, unchanged + * @since 3.2 + */ + public static float CONST(final float v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static double MAGIC_DOUBLE = ObjectUtils.CONST(1.0);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the double value to return + * @return the double v, unchanged + * @since 3.2 + */ + public static double CONST(final double v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static String MAGIC_STRING = ObjectUtils.CONST("abc");
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param the Object type + * @param v the genericized Object value to return (typically a String). + * @return the genericized Object v, unchanged (typically a String). + * @since 3.2 + */ + public static T CONST(final T v) { return v; } + +} diff --git a/Java/commons-lang-ObjectUtils_300/metadata.json b/Java/commons-lang-ObjectUtils_300/metadata.json new file mode 100644 index 000000000..aff44eae9 --- /dev/null +++ b/Java/commons-lang-ObjectUtils_300/metadata.json @@ -0,0 +1,21 @@ +{ + "language": "java", + "id": "commons-lang-ObjectUtils_300", + "buggyPath": ".", + "referencePath": null, + "buildCommand": "mvn package -V -B -Denforcer.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true -Drat.skip=true -Dlicense.skip=true -Dfindbugs.skip=true -Dgpg.skip=true -Dskip.npm=true -Dskip.gulp=true -Dskip.bower=true -Drat.numUnapprovedLicenses=100 -DskipTests=true -DskipITs=true -Dtest=None -DfailIfNoTests=false", + "testCommand": "mvn test -V -B -Denforcer.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true -Drat.skip=true -Dlicense.skip=true -Dfindbugs.skip=true -Dgpg.skip=true -Dskip.npm=true -Dskip.gulp=true -Dskip.bower=true -Drat.numUnapprovedLicenses=100", + "categories": [ + "safety", + "npe" + ], + "npe": { + "filepath": "src/main/java/org/apache/commons/lang3/ObjectUtils.java", + "line": 325, + "npe_method": "hashCodeMulti", + "deref_field": "objects", + "npe_class": "ObjectUtils", + "repo": "commons-lang", + "bug_id": "ObjectUtils_300" + } +} diff --git a/Java/commons-lang-ObjectUtils_300/npe.json b/Java/commons-lang-ObjectUtils_300/npe.json new file mode 100644 index 000000000..de72345a0 --- /dev/null +++ b/Java/commons-lang-ObjectUtils_300/npe.json @@ -0,0 +1,7 @@ +{ + "filepath": "src/main/java/org/apache/commons/lang3/ObjectUtils.java", + "line": 325, + "npe_method": "hashCodeMulti", + "deref_field": "objects", + "npe_class": "ObjectUtils" +} \ No newline at end of file diff --git a/Java/commons-lang-ObjectUtils_328/Dockerfile b/Java/commons-lang-ObjectUtils_328/Dockerfile new file mode 100644 index 000000000..7b7fbe349 --- /dev/null +++ b/Java/commons-lang-ObjectUtils_328/Dockerfile @@ -0,0 +1,18 @@ +FROM ghcr.io/kupl/starlab-benchmarks/java-base:commons-lang + +ENV TZ=Asia/Seoul + +COPY ./metadata.json . +COPY ./npe.json . +COPY ./buggy.java /tmp/buggy.java +RUN export BUGGY_PATH=$(cat metadata.json | jq -r ".npe.filepath") \ + && export BUGGY_LINE=$(cat metadata.json | jq -r ".npe.line") \ + && export BUGGY_MTHD=$(cat metadata.json | jq -r ".npe.npe_method") \ + && mv /tmp/buggy.java $BUGGY_PATH \ + && echo "[{\"filepath\": \"$BUGGY_PATH\", \"line\": $BUGGY_LINE, \"method_name\": \"$BUGGY_MTHD\"}]" | jq . > traces.json + +RUN git init . && git add -A + +RUN $(cat metadata.json | jq -r ".buildCommand") + +RUN $(cat metadata.json | jq -r ".testCommand"); if [ $? -eq 0 ]; then exit 1; fi diff --git a/Java/commons-lang-ObjectUtils_328/buggy.java b/Java/commons-lang-ObjectUtils_328/buggy.java new file mode 100644 index 000000000..3f0c1e7ad --- /dev/null +++ b/Java/commons-lang-ObjectUtils_328/buggy.java @@ -0,0 +1,1035 @@ +/* + * 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.Serializable; +import java.lang.reflect.Array; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.Map; +import java.util.TreeSet; + +import org.apache.commons.lang3.exception.CloneFailedException; +import org.apache.commons.lang3.mutable.MutableInt; +import org.apache.commons.lang3.text.StrBuilder; + +/** + *

Operations on {@code Object}.

+ * + *

This class tries to handle {@code null} input gracefully. + * An exception will generally not be thrown for a {@code null} input. + * Each method documents its behaviour in more detail.

+ * + *

#ThreadSafe#

+ * @since 1.0 + */ +//@Immutable +public class ObjectUtils { + + /** + *

Singleton used as a {@code null} placeholder where + * {@code null} has another meaning.

+ * + *

For example, in a {@code HashMap} the + * {@link java.util.HashMap#get(java.lang.Object)} method returns + * {@code null} if the {@code Map} contains {@code null} or if there + * is no matching key. The {@code Null} placeholder can be used to + * distinguish between these two cases.

+ * + *

Another example is {@code Hashtable}, where {@code null} + * cannot be stored.

+ * + *

This instance is Serializable.

+ */ + public static final Null NULL = new Null(); + + /** + *

{@code ObjectUtils} instances should NOT be constructed in + * standard programming. Instead, the static methods on the class should + * be used, such as {@code ObjectUtils.defaultIfNull("a","b");}.

+ * + *

This constructor is public to permit tools that require a JavaBean + * instance to operate.

+ */ + public ObjectUtils() { + super(); + } + + // Defaulting + //----------------------------------------------------------------------- + /** + *

Returns a default value if the object passed is {@code null}.

+ * + *
+     * ObjectUtils.defaultIfNull(null, null)      = null
+     * ObjectUtils.defaultIfNull(null, "")        = ""
+     * ObjectUtils.defaultIfNull(null, "zz")      = "zz"
+     * ObjectUtils.defaultIfNull("abc", *)        = "abc"
+     * ObjectUtils.defaultIfNull(Boolean.TRUE, *) = Boolean.TRUE
+     * 
+ * + * @param the type of the object + * @param object the {@code Object} to test, may be {@code null} + * @param defaultValue the default value to return, may be {@code null} + * @return {@code object} if it is not {@code null}, defaultValue otherwise + */ + public static T defaultIfNull(final T object, final T defaultValue) { + return object != null ? object : defaultValue; + } + + /** + *

Returns the first value in the array which is not {@code null}. + * If all the values are {@code null} or the array is {@code null} + * or empty then {@code null} is returned.

+ * + *
+     * ObjectUtils.firstNonNull(null, null)      = null
+     * ObjectUtils.firstNonNull(null, "")        = ""
+     * ObjectUtils.firstNonNull(null, null, "")  = ""
+     * ObjectUtils.firstNonNull(null, "zz")      = "zz"
+     * ObjectUtils.firstNonNull("abc", *)        = "abc"
+     * ObjectUtils.firstNonNull(null, "xyz", *)  = "xyz"
+     * ObjectUtils.firstNonNull(Boolean.TRUE, *) = Boolean.TRUE
+     * ObjectUtils.firstNonNull()                = null
+     * 
+ * + * @param the component type of the array + * @param values the values to test, may be {@code null} or empty + * @return the first value from {@code values} which is not {@code null}, + * or {@code null} if there are no non-null values + * @since 3.0 + */ + public static T firstNonNull(final T... values) { + if (values != null) { + for (final T val : values) { + if (val != null) { + return val; + } + } + } + return null; + } + + /** + * Checks if any value in the given array is not {@code null}. + * + *

+ * If all the values are {@code null} or the array is {@code null} + * or empty then {@code false} is returned. Otherwise {@code true} is returned. + *

+ * + *
+     * ObjectUtils.anyNotNull(*)                = true
+     * ObjectUtils.anyNotNull(*, null)          = true
+     * ObjectUtils.anyNotNull(null, *)          = true
+     * ObjectUtils.anyNotNull(null, null, *, *) = true
+     * ObjectUtils.anyNotNull(null)             = false
+     * ObjectUtils.anyNotNull(null, null)       = false
+     * 
+ * + * @param values the values to test, may be {@code null} or empty + * @return {@code true} if there is at least one non-null value in the array, + * {@code false} if all values in the array are {@code null}s. + * If the array is {@code null} or empty {@code false} is also returned. + * @since 3.5 + */ + public static boolean anyNotNull(final Object... values) { + return firstNonNull(values) != null; + } + + /** + * Checks if all values in the array are not {@code nulls}. + * + *

+ * If any value is {@code null} or the array is {@code null} then + * {@code false} is returned. If all elements in array are not + * {@code null} or the array is empty (contains no elements) {@code true} + * is returned. + *

+ * + *
+     * ObjectUtils.allNotNull(*)             = true
+     * ObjectUtils.allNotNull(*, *)          = true
+     * ObjectUtils.allNotNull(null)          = false
+     * ObjectUtils.allNotNull(null, null)    = false
+     * ObjectUtils.allNotNull(null, *)       = false
+     * ObjectUtils.allNotNull(*, null)       = false
+     * ObjectUtils.allNotNull(*, *, null, *) = false
+     * 
+ * + * @param values the values to test, may be {@code null} or empty + * @return {@code false} if there is at least one {@code null} value in the array or the array is {@code null}, + * {@code true} if all values in the array are not {@code null}s or array contains no elements. + * @since 3.5 + */ + public static boolean allNotNull(final Object... values) { + if (values == null) { + return false; + } + + for (final Object val : values) { + if (val == null) { + return false; + } + } + + return true; + } + + // Null-safe equals/hashCode + //----------------------------------------------------------------------- + /** + *

Compares two objects for equality, where either one or both + * objects may be {@code null}.

+ * + *
+     * ObjectUtils.equals(null, null)                  = true
+     * ObjectUtils.equals(null, "")                    = false
+     * ObjectUtils.equals("", null)                    = false
+     * ObjectUtils.equals("", "")                      = true
+     * ObjectUtils.equals(Boolean.TRUE, null)          = false
+     * ObjectUtils.equals(Boolean.TRUE, "true")        = false
+     * ObjectUtils.equals(Boolean.TRUE, Boolean.TRUE)  = true
+     * ObjectUtils.equals(Boolean.TRUE, Boolean.FALSE) = false
+     * 
+ * + * @param object1 the first object, may be {@code null} + * @param object2 the second object, may be {@code null} + * @return {@code true} if the values of both objects are the same + * @deprecated this method has been replaced by {@code java.util.Objects.equals(Object, Object)} in Java 7 and will + * be removed from future releases. + */ + @Deprecated + public static boolean equals(final Object object1, final Object object2) { + if (object1 == object2) { + return true; + } + if (object1 == null || object2 == null) { + return false; + } + return object1.equals(object2); + } + + /** + *

Compares two objects for inequality, where either one or both + * objects may be {@code null}.

+ * + *
+     * ObjectUtils.notEqual(null, null)                  = false
+     * ObjectUtils.notEqual(null, "")                    = true
+     * ObjectUtils.notEqual("", null)                    = true
+     * ObjectUtils.notEqual("", "")                      = false
+     * ObjectUtils.notEqual(Boolean.TRUE, null)          = true
+     * ObjectUtils.notEqual(Boolean.TRUE, "true")        = true
+     * ObjectUtils.notEqual(Boolean.TRUE, Boolean.TRUE)  = false
+     * ObjectUtils.notEqual(Boolean.TRUE, Boolean.FALSE) = true
+     * 
+ * + * @param object1 the first object, may be {@code null} + * @param object2 the second object, may be {@code null} + * @return {@code false} if the values of both objects are the same + */ + public static boolean notEqual(final Object object1, final Object object2) { + return ObjectUtils.equals(object1, object2) == false; + } + + /** + *

Gets the hash code of an object returning zero when the + * object is {@code null}.

+ * + *
+     * ObjectUtils.hashCode(null)   = 0
+     * ObjectUtils.hashCode(obj)    = obj.hashCode()
+     * 
+ * + * @param obj the object to obtain the hash code of, may be {@code null} + * @return the hash code of the object, or zero if null + * @since 2.1 + * @deprecated this method has been replaced by {@code java.util.Objects.hashCode(Object)} in Java 7 and will be + * removed in future releases + */ + @Deprecated + public static int hashCode(final Object obj) { + // hashCode(Object) retained for performance, as hash code is often critical + return obj == null ? 0 : obj.hashCode(); + } + + /** + *

Gets the hash code for multiple objects.

+ * + *

This allows a hash code to be rapidly calculated for a number of objects. + * The hash code for a single object is the not same as {@link #hashCode(Object)}. + * The hash code for multiple objects is the same as that calculated by an + * {@code ArrayList} containing the specified objects.

+ * + *
+     * ObjectUtils.hashCodeMulti()                 = 1
+     * ObjectUtils.hashCodeMulti((Object[]) null)  = 1
+     * ObjectUtils.hashCodeMulti(a)                = 31 + a.hashCode()
+     * ObjectUtils.hashCodeMulti(a,b)              = (31 + a.hashCode()) * 31 + b.hashCode()
+     * ObjectUtils.hashCodeMulti(a,b,c)            = ((31 + a.hashCode()) * 31 + b.hashCode()) * 31 + c.hashCode()
+     * 
+ * + * @param objects the objects to obtain the hash code of, may be {@code null} + * @return the hash code of the objects, or zero if null + * @since 3.0 + * @deprecated this method has been replaced by {@code java.util.Objects.hash(Object...)} in Java 7 and will be + * removed in future releases. + */ + @Deprecated + public static int hashCodeMulti(final Object... objects) { + int hash = 1; + if (objects != null) { + for (final Object object : objects) { + final int tmpHash = ObjectUtils.hashCode(object); + hash = hash * 31 + tmpHash; + } + } + return hash; + } + + // Identity ToString + //----------------------------------------------------------------------- + /** + *

Gets the toString that would be produced by {@code Object} + * if a class did not override toString itself. {@code null} + * will return {@code null}.

+ * + *
+     * ObjectUtils.identityToString(null)         = null
+     * ObjectUtils.identityToString("")           = "java.lang.String@1e23"
+     * ObjectUtils.identityToString(Boolean.TRUE) = "java.lang.Boolean@7fa"
+     * 
+ * + * @param object the object to create a toString for, may be + * {@code null} + * @return the default toString text, or {@code null} if + * {@code null} passed in + */ +// Identity ToString +// ----------------------------------------------------------------------- +/** + *

Gets the toString that would be produced by {@code Object} + * if a class did not override toString itself. {@code null} + * will return {@code null}.

+ * + *
+ * ObjectUtils.identityToString(null)         = null
+ * ObjectUtils.identityToString("")           = "java.lang.String@1e23"
+ * ObjectUtils.identityToString(Boolean.TRUE) = "java.lang.Boolean@7fa"
+ * 
+ * + * @param object + * the object to create a toString for, may be + * {@code null} + * @return the default toString text, or {@code null} if +{@code null} passed in + */ +public static java.lang.String identityToString(final java.lang.Object object) { + { + final java.lang.StringBuilder builder = new java.lang.StringBuilder(); + org.apache.commons.lang3.ObjectUtils.identityToString(builder, /* NPEX_NULL_EXP */ + object); + return builder.toString(); + } +} + + /** + *

Appends the toString that would be produced by {@code Object} + * if a class did not override toString itself. {@code null} + * will throw a NullPointerException for either of the two parameters.

+ * + *
+     * ObjectUtils.identityToString(appendable, "")            = appendable.append("java.lang.String@1e23"
+     * ObjectUtils.identityToString(appendable, Boolean.TRUE)  = appendable.append("java.lang.Boolean@7fa"
+     * ObjectUtils.identityToString(appendable, Boolean.TRUE)  = appendable.append("java.lang.Boolean@7fa")
+     * 
+ * + * @param appendable the appendable to append to + * @param object the object to create a toString for + * @throws IOException if an I/O error occurs + * @since 3.2 + */ + public static void identityToString(final Appendable appendable, final Object object) throws IOException { + if (object == null) { + throw new NullPointerException("Cannot get the toString of a null identity"); + } + appendable.append(object.getClass().getName()) + .append('@') + .append(Integer.toHexString(System.identityHashCode(object))); + } + + /** + *

Appends the toString that would be produced by {@code Object} + * if a class did not override toString itself. {@code null} + * will throw a NullPointerException for either of the two parameters.

+ * + *
+     * ObjectUtils.identityToString(builder, "")            = builder.append("java.lang.String@1e23"
+     * ObjectUtils.identityToString(builder, Boolean.TRUE)  = builder.append("java.lang.Boolean@7fa"
+     * ObjectUtils.identityToString(builder, Boolean.TRUE)  = builder.append("java.lang.Boolean@7fa")
+     * 
+ * + * @param builder the builder to append to + * @param object the object to create a toString for + * @since 3.2 + */ + public static void identityToString(final StrBuilder builder, final Object object) { + if (object == null) { + throw new NullPointerException("Cannot get the toString of a null identity"); + } + builder.append(object.getClass().getName()) + .append('@') + .append(Integer.toHexString(System.identityHashCode(object))); + } + + /** + *

Appends the toString that would be produced by {@code Object} + * if a class did not override toString itself. {@code null} + * will throw a NullPointerException for either of the two parameters.

+ * + *
+     * ObjectUtils.identityToString(buf, "")            = buf.append("java.lang.String@1e23"
+     * ObjectUtils.identityToString(buf, Boolean.TRUE)  = buf.append("java.lang.Boolean@7fa"
+     * ObjectUtils.identityToString(buf, Boolean.TRUE)  = buf.append("java.lang.Boolean@7fa")
+     * 
+ * + * @param buffer the buffer to append to + * @param object the object to create a toString for + * @since 2.4 + */ + public static void identityToString(final StringBuffer buffer, final Object object) { + if (object == null) { + throw new NullPointerException("Cannot get the toString of a null identity"); + } + buffer.append(object.getClass().getName()) + .append('@') + .append(Integer.toHexString(System.identityHashCode(object))); + } + + /** + *

Appends the toString that would be produced by {@code Object} + * if a class did not override toString itself. {@code null} + * will throw a NullPointerException for either of the two parameters.

+ * + *
+     * ObjectUtils.identityToString(builder, "")            = builder.append("java.lang.String@1e23"
+     * ObjectUtils.identityToString(builder, Boolean.TRUE)  = builder.append("java.lang.Boolean@7fa"
+     * ObjectUtils.identityToString(builder, Boolean.TRUE)  = builder.append("java.lang.Boolean@7fa")
+     * 
+ * + * @param builder the builder to append to + * @param object the object to create a toString for + * @since 3.2 + */ + public static void identityToString(final StringBuilder builder, final Object object) { + if (object == null) { + throw new NullPointerException("Cannot get the toString of a null identity"); + } + builder.append(object.getClass().getName()) + .append('@') + .append(Integer.toHexString(System.identityHashCode(object))); + } + + // ToString + //----------------------------------------------------------------------- + /** + *

Gets the {@code toString} of an {@code Object} returning + * an empty string ("") if {@code null} input.

+ * + *
+     * ObjectUtils.toString(null)         = ""
+     * ObjectUtils.toString("")           = ""
+     * ObjectUtils.toString("bat")        = "bat"
+     * ObjectUtils.toString(Boolean.TRUE) = "true"
+     * 
+ * + * @see StringUtils#defaultString(String) + * @see String#valueOf(Object) + * @param obj the Object to {@code toString}, may be null + * @return the passed in Object's toString, or {@code ""} if {@code null} input + * @since 2.0 + * @deprecated this method has been replaced by {@code java.util.Objects.toString(Object)} in Java 7 and will be + * removed in future releases. Note however that said method will return "null" for null references, while this + * method returns and empty String. To preserve behavior use {@code java.util.Objects.toString(myObject, "")} + */ + @Deprecated + public static String toString(final Object obj) { + return obj == null ? StringUtils.EMPTY : obj.toString(); + } + + /** + *

Gets the {@code toString} of an {@code Object} returning + * a specified text if {@code null} input.

+ * + *
+     * ObjectUtils.toString(null, null)           = null
+     * ObjectUtils.toString(null, "null")         = "null"
+     * ObjectUtils.toString("", "null")           = ""
+     * ObjectUtils.toString("bat", "null")        = "bat"
+     * ObjectUtils.toString(Boolean.TRUE, "null") = "true"
+     * 
+ * + * @see StringUtils#defaultString(String,String) + * @see String#valueOf(Object) + * @param obj the Object to {@code toString}, may be null + * @param nullStr the String to return if {@code null} input, may be null + * @return the passed in Object's toString, or {@code nullStr} if {@code null} input + * @since 2.0 + * @deprecated this method has been replaced by {@code java.util.Objects.toString(Object, String)} in Java 7 and + * will be removed in future releases. + */ + @Deprecated + public static String toString(final Object obj, final String nullStr) { + return obj == null ? nullStr : obj.toString(); + } + + // Comparable + //----------------------------------------------------------------------- + /** + *

Null safe comparison of Comparables.

+ * + * @param type of the values processed by this method + * @param values the set of comparable values, may be null + * @return + *
    + *
  • If any objects are non-null and unequal, the lesser object. + *
  • If all objects are non-null and equal, the first. + *
  • If any of the comparables are null, the lesser of the non-null objects. + *
  • If all the comparables are null, null is returned. + *
+ */ + public static > T min(final T... values) { + T result = null; + if (values != null) { + for (final T value : values) { + if (compare(value, result, true) < 0) { + result = value; + } + } + } + return result; + } + + /** + *

Null safe comparison of Comparables.

+ * + * @param type of the values processed by this method + * @param values the set of comparable values, may be null + * @return + *
    + *
  • If any objects are non-null and unequal, the greater object. + *
  • If all objects are non-null and equal, the first. + *
  • If any of the comparables are null, the greater of the non-null objects. + *
  • If all the comparables are null, null is returned. + *
+ */ + public static > T max(final T... values) { + T result = null; + if (values != null) { + for (final T value : values) { + if (compare(value, result, false) > 0) { + result = value; + } + } + } + return result; + } + + /** + *

Null safe comparison of Comparables. + * {@code null} is assumed to be less than a non-{@code null} value.

+ * + * @param type of the values processed by this method + * @param c1 the first comparable, may be null + * @param c2 the second comparable, may be null + * @return a negative value if c1 < c2, zero if c1 = c2 + * and a positive value if c1 > c2 + */ + public static > int compare(final T c1, final T c2) { + return compare(c1, c2, false); + } + + /** + *

Null safe comparison of Comparables.

+ * + * @param type of the values processed by this method + * @param c1 the first comparable, may be null + * @param c2 the second comparable, may be null + * @param nullGreater if true {@code null} is considered greater + * than a non-{@code null} value or if false {@code null} is + * considered less than a Non-{@code null} value + * @return a negative value if c1 < c2, zero if c1 = c2 + * and a positive value if c1 > c2 + * @see java.util.Comparator#compare(Object, Object) + */ + public static > int compare(final T c1, final T c2, final boolean nullGreater) { + if (c1 == c2) { + return 0; + } else if (c1 == null) { + return nullGreater ? 1 : -1; + } else if (c2 == null) { + return nullGreater ? -1 : 1; + } + return c1.compareTo(c2); + } + + /** + * Find the "best guess" middle value among comparables. If there is an even + * number of total values, the lower of the two middle values will be returned. + * @param type of values processed by this method + * @param items to compare + * @return T at middle position + * @throws NullPointerException if items is {@code null} + * @throws IllegalArgumentException if items is empty or contains {@code null} values + * @since 3.0.1 + */ + public static > T median(final T... items) { + Validate.notEmpty(items); + Validate.noNullElements(items); + final TreeSet sort = new TreeSet(); + Collections.addAll(sort, items); + @SuppressWarnings("unchecked") //we know all items added were T instances + final + T result = (T) sort.toArray()[(sort.size() - 1) / 2]; + return result; + } + + /** + * Find the "best guess" middle value among comparables. If there is an even + * number of total values, the lower of the two middle values will be returned. + * @param type of values processed by this method + * @param comparator to use for comparisons + * @param items to compare + * @return T at middle position + * @throws NullPointerException if items or comparator is {@code null} + * @throws IllegalArgumentException if items is empty or contains {@code null} values + * @since 3.0.1 + */ + public static T median(final Comparator comparator, final T... items) { + Validate.notEmpty(items, "null/empty items"); + Validate.noNullElements(items); + Validate.notNull(comparator, "null comparator"); + final TreeSet sort = new TreeSet(comparator); + Collections.addAll(sort, items); + @SuppressWarnings("unchecked") //we know all items added were T instances + final + T result = (T) sort.toArray()[(sort.size() - 1) / 2]; + return result; + } + + // Mode + //----------------------------------------------------------------------- + /** + * Find the most frequently occurring item. + * + * @param type of values processed by this method + * @param items to check + * @return most populous T, {@code null} if non-unique or no items supplied + * @since 3.0.1 + */ + public static T mode(final T... items) { + if (ArrayUtils.isNotEmpty(items)) { + final HashMap occurrences = new HashMap(items.length); + for (final T t : items) { + final MutableInt count = occurrences.get(t); + if (count == null) { + occurrences.put(t, new MutableInt(1)); + } else { + count.increment(); + } + } + T result = null; + int max = 0; + for (final Map.Entry e : occurrences.entrySet()) { + final int cmp = e.getValue().intValue(); + if (cmp == max) { + result = null; + } else if (cmp > max) { + max = cmp; + result = e.getKey(); + } + } + return result; + } + return null; + } + + // cloning + //----------------------------------------------------------------------- + /** + *

Clone an object.

+ * + * @param the type of the object + * @param obj the object to clone, null returns null + * @return the clone if the object implements {@link Cloneable} otherwise {@code null} + * @throws CloneFailedException if the object is cloneable and the clone operation fails + * @since 3.0 + */ + public static T clone(final T obj) { + if (obj instanceof Cloneable) { + final Object result; + if (obj.getClass().isArray()) { + final Class componentType = obj.getClass().getComponentType(); + if (!componentType.isPrimitive()) { + result = ((Object[]) obj).clone(); + } else { + int length = Array.getLength(obj); + result = Array.newInstance(componentType, length); + while (length-- > 0) { + Array.set(result, length, Array.get(obj, length)); + } + } + } else { + try { + final Method clone = obj.getClass().getMethod("clone"); + result = clone.invoke(obj); + } catch (final NoSuchMethodException e) { + throw new CloneFailedException("Cloneable type " + + obj.getClass().getName() + + " has no clone method", e); + } catch (final IllegalAccessException e) { + throw new CloneFailedException("Cannot clone Cloneable type " + + obj.getClass().getName(), e); + } catch (final InvocationTargetException e) { + throw new CloneFailedException("Exception cloning Cloneable type " + + obj.getClass().getName(), e.getCause()); + } + } + @SuppressWarnings("unchecked") // OK because input is of type T + final T checked = (T) result; + return checked; + } + + return null; + } + + /** + *

Clone an object if possible.

+ * + *

This method is similar to {@link #clone(Object)}, but will return the provided + * instance as the return value instead of {@code null} if the instance + * is not cloneable. This is more convenient if the caller uses different + * implementations (e.g. of a service) and some of the implementations do not allow concurrent + * processing or have state. In such cases the implementation can simply provide a proper + * clone implementation and the caller's code does not have to change.

+ * + * @param the type of the object + * @param obj the object to clone, null returns null + * @return the clone if the object implements {@link Cloneable} otherwise the object itself + * @throws CloneFailedException if the object is cloneable and the clone operation fails + * @since 3.0 + */ + public static T cloneIfPossible(final T obj) { + final T clone = clone(obj); + return clone == null ? obj : clone; + } + + // Null + //----------------------------------------------------------------------- + /** + *

Class used as a null placeholder where {@code null} + * has another meaning.

+ * + *

For example, in a {@code HashMap} the + * {@link java.util.HashMap#get(java.lang.Object)} method returns + * {@code null} if the {@code Map} contains {@code null} or if there is + * no matching key. The {@code Null} placeholder can be used to distinguish + * between these two cases.

+ * + *

Another example is {@code Hashtable}, where {@code null} + * cannot be stored.

+ */ + public static class Null implements Serializable { + /** + * Required for serialization support. Declare serialization compatibility with Commons Lang 1.0 + * + * @see java.io.Serializable + */ + private static final long serialVersionUID = 7092611880189329093L; + + /** + * Restricted constructor - singleton. + */ + Null() { + super(); + } + + /** + *

Ensure singleton.

+ * + * @return the singleton value + */ + private Object readResolve() { + return ObjectUtils.NULL; + } + } + + + // Constants (LANG-816): + /* + These methods ensure constants are not inlined by javac. + For example, typically a developer might declare a constant like so: + + public final static int MAGIC_NUMBER = 5; + + Should a different jar file refer to this, and the MAGIC_NUMBER + is changed a later date (e.g., MAGIC_NUMBER = 6), the different jar + file will need to recompile itself. This is because javac + typically inlines the primitive or String constant directly into + the bytecode, and removes the reference to the MAGIC_NUMBER field. + + To help the other jar (so that it does not need to recompile + when constants are changed) the original developer can declare + their constant using one of the CONST() utility methods, instead: + + public final static int MAGIC_NUMBER = CONST(5); + */ + + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static boolean MAGIC_FLAG = ObjectUtils.CONST(true);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the boolean value to return + * @return the boolean v, unchanged + * @since 3.2 + */ + public static boolean CONST(final boolean v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static byte MAGIC_BYTE = ObjectUtils.CONST((byte) 127);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the byte value to return + * @return the byte v, unchanged + * @since 3.2 + */ + public static byte CONST(final byte v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static byte MAGIC_BYTE = ObjectUtils.CONST_BYTE(127);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the byte literal (as an int) value to return + * @throws IllegalArgumentException if the value passed to v + * is larger than a byte, that is, smaller than -128 or + * larger than 127. + * @return the byte v, unchanged + * @since 3.2 + */ + public static byte CONST_BYTE(final int v) throws IllegalArgumentException { + if (v < Byte.MIN_VALUE || v > Byte.MAX_VALUE) { + throw new IllegalArgumentException("Supplied value must be a valid byte literal between -128 and 127: [" + v + "]"); + } + return (byte) v; + } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static char MAGIC_CHAR = ObjectUtils.CONST('a');
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the char value to return + * @return the char v, unchanged + * @since 3.2 + */ + public static char CONST(final char v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static short MAGIC_SHORT = ObjectUtils.CONST((short) 123);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the short value to return + * @return the short v, unchanged + * @since 3.2 + */ + public static short CONST(final short v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static short MAGIC_SHORT = ObjectUtils.CONST_SHORT(127);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the short literal (as an int) value to return + * @throws IllegalArgumentException if the value passed to v + * is larger than a short, that is, smaller than -32768 or + * larger than 32767. + * @return the byte v, unchanged + * @since 3.2 + */ + public static short CONST_SHORT(final int v) throws IllegalArgumentException { + if (v < Short.MIN_VALUE || v > Short.MAX_VALUE) { + throw new IllegalArgumentException("Supplied value must be a valid byte literal between -32768 and 32767: [" + v + "]"); + } + return (short) v; + } + + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static int MAGIC_INT = ObjectUtils.CONST(123);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the int value to return + * @return the int v, unchanged + * @since 3.2 + */ + public static int CONST(final int v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static long MAGIC_LONG = ObjectUtils.CONST(123L);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the long value to return + * @return the long v, unchanged + * @since 3.2 + */ + public static long CONST(final long v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static float MAGIC_FLOAT = ObjectUtils.CONST(1.0f);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the float value to return + * @return the float v, unchanged + * @since 3.2 + */ + public static float CONST(final float v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static double MAGIC_DOUBLE = ObjectUtils.CONST(1.0);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the double value to return + * @return the double v, unchanged + * @since 3.2 + */ + public static double CONST(final double v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static String MAGIC_STRING = ObjectUtils.CONST("abc");
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param the Object type + * @param v the genericized Object value to return (typically a String). + * @return the genericized Object v, unchanged (typically a String). + * @since 3.2 + */ + public static T CONST(final T v) { return v; } + +} diff --git a/Java/commons-lang-ObjectUtils_328/metadata.json b/Java/commons-lang-ObjectUtils_328/metadata.json new file mode 100644 index 000000000..7184dbaf3 --- /dev/null +++ b/Java/commons-lang-ObjectUtils_328/metadata.json @@ -0,0 +1,21 @@ +{ + "language": "java", + "id": "commons-lang-ObjectUtils_328", + "buggyPath": ".", + "referencePath": null, + "buildCommand": "mvn package -V -B -Denforcer.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true -Drat.skip=true -Dlicense.skip=true -Dfindbugs.skip=true -Dgpg.skip=true -Dskip.npm=true -Dskip.gulp=true -Dskip.bower=true -Drat.numUnapprovedLicenses=100 -DskipTests=true -DskipITs=true -Dtest=None -DfailIfNoTests=false", + "testCommand": "mvn test -V -B -Denforcer.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true -Drat.skip=true -Dlicense.skip=true -Dfindbugs.skip=true -Dgpg.skip=true -Dskip.npm=true -Dskip.gulp=true -Dskip.bower=true -Drat.numUnapprovedLicenses=100", + "categories": [ + "safety", + "npe" + ], + "npe": { + "filepath": "src/main/java/org/apache/commons/lang3/ObjectUtils.java", + "line": 350, + "npe_method": "identityToString", + "deref_field": "object", + "npe_class": "ObjectUtils", + "repo": "commons-lang", + "bug_id": "ObjectUtils_328" + } +} diff --git a/Java/commons-lang-ObjectUtils_328/npe.json b/Java/commons-lang-ObjectUtils_328/npe.json new file mode 100644 index 000000000..af76f316f --- /dev/null +++ b/Java/commons-lang-ObjectUtils_328/npe.json @@ -0,0 +1,7 @@ +{ + "filepath": "src/main/java/org/apache/commons/lang3/ObjectUtils.java", + "line": 350, + "npe_method": "identityToString", + "deref_field": "object", + "npe_class": "ObjectUtils" +} \ No newline at end of file diff --git a/Java/commons-lang-ObjectUtils_457/Dockerfile b/Java/commons-lang-ObjectUtils_457/Dockerfile new file mode 100644 index 000000000..7b7fbe349 --- /dev/null +++ b/Java/commons-lang-ObjectUtils_457/Dockerfile @@ -0,0 +1,18 @@ +FROM ghcr.io/kupl/starlab-benchmarks/java-base:commons-lang + +ENV TZ=Asia/Seoul + +COPY ./metadata.json . +COPY ./npe.json . +COPY ./buggy.java /tmp/buggy.java +RUN export BUGGY_PATH=$(cat metadata.json | jq -r ".npe.filepath") \ + && export BUGGY_LINE=$(cat metadata.json | jq -r ".npe.line") \ + && export BUGGY_MTHD=$(cat metadata.json | jq -r ".npe.npe_method") \ + && mv /tmp/buggy.java $BUGGY_PATH \ + && echo "[{\"filepath\": \"$BUGGY_PATH\", \"line\": $BUGGY_LINE, \"method_name\": \"$BUGGY_MTHD\"}]" | jq . > traces.json + +RUN git init . && git add -A + +RUN $(cat metadata.json | jq -r ".buildCommand") + +RUN $(cat metadata.json | jq -r ".testCommand"); if [ $? -eq 0 ]; then exit 1; fi diff --git a/Java/commons-lang-ObjectUtils_457/buggy.java b/Java/commons-lang-ObjectUtils_457/buggy.java new file mode 100644 index 000000000..d88cc9e99 --- /dev/null +++ b/Java/commons-lang-ObjectUtils_457/buggy.java @@ -0,0 +1,1040 @@ +/* + * 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.Serializable; +import java.lang.reflect.Array; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.Map; +import java.util.TreeSet; + +import org.apache.commons.lang3.exception.CloneFailedException; +import org.apache.commons.lang3.mutable.MutableInt; +import org.apache.commons.lang3.text.StrBuilder; + +/** + *

Operations on {@code Object}.

+ * + *

This class tries to handle {@code null} input gracefully. + * An exception will generally not be thrown for a {@code null} input. + * Each method documents its behaviour in more detail.

+ * + *

#ThreadSafe#

+ * @since 1.0 + */ +//@Immutable +public class ObjectUtils { + + /** + *

Singleton used as a {@code null} placeholder where + * {@code null} has another meaning.

+ * + *

For example, in a {@code HashMap} the + * {@link java.util.HashMap#get(java.lang.Object)} method returns + * {@code null} if the {@code Map} contains {@code null} or if there + * is no matching key. The {@code Null} placeholder can be used to + * distinguish between these two cases.

+ * + *

Another example is {@code Hashtable}, where {@code null} + * cannot be stored.

+ * + *

This instance is Serializable.

+ */ + public static final Null NULL = new Null(); + + /** + *

{@code ObjectUtils} instances should NOT be constructed in + * standard programming. Instead, the static methods on the class should + * be used, such as {@code ObjectUtils.defaultIfNull("a","b");}.

+ * + *

This constructor is public to permit tools that require a JavaBean + * instance to operate.

+ */ + public ObjectUtils() { + super(); + } + + // Defaulting + //----------------------------------------------------------------------- + /** + *

Returns a default value if the object passed is {@code null}.

+ * + *
+     * ObjectUtils.defaultIfNull(null, null)      = null
+     * ObjectUtils.defaultIfNull(null, "")        = ""
+     * ObjectUtils.defaultIfNull(null, "zz")      = "zz"
+     * ObjectUtils.defaultIfNull("abc", *)        = "abc"
+     * ObjectUtils.defaultIfNull(Boolean.TRUE, *) = Boolean.TRUE
+     * 
+ * + * @param the type of the object + * @param object the {@code Object} to test, may be {@code null} + * @param defaultValue the default value to return, may be {@code null} + * @return {@code object} if it is not {@code null}, defaultValue otherwise + */ + public static T defaultIfNull(final T object, final T defaultValue) { + return object != null ? object : defaultValue; + } + + /** + *

Returns the first value in the array which is not {@code null}. + * If all the values are {@code null} or the array is {@code null} + * or empty then {@code null} is returned.

+ * + *
+     * ObjectUtils.firstNonNull(null, null)      = null
+     * ObjectUtils.firstNonNull(null, "")        = ""
+     * ObjectUtils.firstNonNull(null, null, "")  = ""
+     * ObjectUtils.firstNonNull(null, "zz")      = "zz"
+     * ObjectUtils.firstNonNull("abc", *)        = "abc"
+     * ObjectUtils.firstNonNull(null, "xyz", *)  = "xyz"
+     * ObjectUtils.firstNonNull(Boolean.TRUE, *) = Boolean.TRUE
+     * ObjectUtils.firstNonNull()                = null
+     * 
+ * + * @param the component type of the array + * @param values the values to test, may be {@code null} or empty + * @return the first value from {@code values} which is not {@code null}, + * or {@code null} if there are no non-null values + * @since 3.0 + */ + public static T firstNonNull(final T... values) { + if (values != null) { + for (final T val : values) { + if (val != null) { + return val; + } + } + } + return null; + } + + /** + * Checks if any value in the given array is not {@code null}. + * + *

+ * If all the values are {@code null} or the array is {@code null} + * or empty then {@code false} is returned. Otherwise {@code true} is returned. + *

+ * + *
+     * ObjectUtils.anyNotNull(*)                = true
+     * ObjectUtils.anyNotNull(*, null)          = true
+     * ObjectUtils.anyNotNull(null, *)          = true
+     * ObjectUtils.anyNotNull(null, null, *, *) = true
+     * ObjectUtils.anyNotNull(null)             = false
+     * ObjectUtils.anyNotNull(null, null)       = false
+     * 
+ * + * @param values the values to test, may be {@code null} or empty + * @return {@code true} if there is at least one non-null value in the array, + * {@code false} if all values in the array are {@code null}s. + * If the array is {@code null} or empty {@code false} is also returned. + * @since 3.5 + */ + public static boolean anyNotNull(final Object... values) { + return firstNonNull(values) != null; + } + + /** + * Checks if all values in the array are not {@code nulls}. + * + *

+ * If any value is {@code null} or the array is {@code null} then + * {@code false} is returned. If all elements in array are not + * {@code null} or the array is empty (contains no elements) {@code true} + * is returned. + *

+ * + *
+     * ObjectUtils.allNotNull(*)             = true
+     * ObjectUtils.allNotNull(*, *)          = true
+     * ObjectUtils.allNotNull(null)          = false
+     * ObjectUtils.allNotNull(null, null)    = false
+     * ObjectUtils.allNotNull(null, *)       = false
+     * ObjectUtils.allNotNull(*, null)       = false
+     * ObjectUtils.allNotNull(*, *, null, *) = false
+     * 
+ * + * @param values the values to test, may be {@code null} or empty + * @return {@code false} if there is at least one {@code null} value in the array or the array is {@code null}, + * {@code true} if all values in the array are not {@code null}s or array contains no elements. + * @since 3.5 + */ + public static boolean allNotNull(final Object... values) { + if (values == null) { + return false; + } + + for (final Object val : values) { + if (val == null) { + return false; + } + } + + return true; + } + + // Null-safe equals/hashCode + //----------------------------------------------------------------------- + /** + *

Compares two objects for equality, where either one or both + * objects may be {@code null}.

+ * + *
+     * ObjectUtils.equals(null, null)                  = true
+     * ObjectUtils.equals(null, "")                    = false
+     * ObjectUtils.equals("", null)                    = false
+     * ObjectUtils.equals("", "")                      = true
+     * ObjectUtils.equals(Boolean.TRUE, null)          = false
+     * ObjectUtils.equals(Boolean.TRUE, "true")        = false
+     * ObjectUtils.equals(Boolean.TRUE, Boolean.TRUE)  = true
+     * ObjectUtils.equals(Boolean.TRUE, Boolean.FALSE) = false
+     * 
+ * + * @param object1 the first object, may be {@code null} + * @param object2 the second object, may be {@code null} + * @return {@code true} if the values of both objects are the same + * @deprecated this method has been replaced by {@code java.util.Objects.equals(Object, Object)} in Java 7 and will + * be removed from future releases. + */ + @Deprecated + public static boolean equals(final Object object1, final Object object2) { + if (object1 == object2) { + return true; + } + if (object1 == null || object2 == null) { + return false; + } + return object1.equals(object2); + } + + /** + *

Compares two objects for inequality, where either one or both + * objects may be {@code null}.

+ * + *
+     * ObjectUtils.notEqual(null, null)                  = false
+     * ObjectUtils.notEqual(null, "")                    = true
+     * ObjectUtils.notEqual("", null)                    = true
+     * ObjectUtils.notEqual("", "")                      = false
+     * ObjectUtils.notEqual(Boolean.TRUE, null)          = true
+     * ObjectUtils.notEqual(Boolean.TRUE, "true")        = true
+     * ObjectUtils.notEqual(Boolean.TRUE, Boolean.TRUE)  = false
+     * ObjectUtils.notEqual(Boolean.TRUE, Boolean.FALSE) = true
+     * 
+ * + * @param object1 the first object, may be {@code null} + * @param object2 the second object, may be {@code null} + * @return {@code false} if the values of both objects are the same + */ + public static boolean notEqual(final Object object1, final Object object2) { + return ObjectUtils.equals(object1, object2) == false; + } + + /** + *

Gets the hash code of an object returning zero when the + * object is {@code null}.

+ * + *
+     * ObjectUtils.hashCode(null)   = 0
+     * ObjectUtils.hashCode(obj)    = obj.hashCode()
+     * 
+ * + * @param obj the object to obtain the hash code of, may be {@code null} + * @return the hash code of the object, or zero if null + * @since 2.1 + * @deprecated this method has been replaced by {@code java.util.Objects.hashCode(Object)} in Java 7 and will be + * removed in future releases + */ + @Deprecated + public static int hashCode(final Object obj) { + // hashCode(Object) retained for performance, as hash code is often critical + return obj == null ? 0 : obj.hashCode(); + } + + /** + *

Gets the hash code for multiple objects.

+ * + *

This allows a hash code to be rapidly calculated for a number of objects. + * The hash code for a single object is the not same as {@link #hashCode(Object)}. + * The hash code for multiple objects is the same as that calculated by an + * {@code ArrayList} containing the specified objects.

+ * + *
+     * ObjectUtils.hashCodeMulti()                 = 1
+     * ObjectUtils.hashCodeMulti((Object[]) null)  = 1
+     * ObjectUtils.hashCodeMulti(a)                = 31 + a.hashCode()
+     * ObjectUtils.hashCodeMulti(a,b)              = (31 + a.hashCode()) * 31 + b.hashCode()
+     * ObjectUtils.hashCodeMulti(a,b,c)            = ((31 + a.hashCode()) * 31 + b.hashCode()) * 31 + c.hashCode()
+     * 
+ * + * @param objects the objects to obtain the hash code of, may be {@code null} + * @return the hash code of the objects, or zero if null + * @since 3.0 + * @deprecated this method has been replaced by {@code java.util.Objects.hash(Object...)} in Java 7 and will be + * removed in future releases. + */ + @Deprecated + public static int hashCodeMulti(final Object... objects) { + int hash = 1; + if (objects != null) { + for (final Object object : objects) { + final int tmpHash = ObjectUtils.hashCode(object); + hash = hash * 31 + tmpHash; + } + } + return hash; + } + + // Identity ToString + //----------------------------------------------------------------------- + /** + *

Gets the toString that would be produced by {@code Object} + * if a class did not override toString itself. {@code null} + * will return {@code null}.

+ * + *
+     * ObjectUtils.identityToString(null)         = null
+     * ObjectUtils.identityToString("")           = "java.lang.String@1e23"
+     * ObjectUtils.identityToString(Boolean.TRUE) = "java.lang.Boolean@7fa"
+     * 
+ * + * @param object the object to create a toString for, may be + * {@code null} + * @return the default toString text, or {@code null} if + * {@code null} passed in + */ + public static String identityToString(final Object object) { + if (object == null) { + return null; + } + final StringBuilder builder = new StringBuilder(); + identityToString(builder, object); + return builder.toString(); + } + + /** + *

Appends the toString that would be produced by {@code Object} + * if a class did not override toString itself. {@code null} + * will throw a NullPointerException for either of the two parameters.

+ * + *
+     * ObjectUtils.identityToString(appendable, "")            = appendable.append("java.lang.String@1e23"
+     * ObjectUtils.identityToString(appendable, Boolean.TRUE)  = appendable.append("java.lang.Boolean@7fa"
+     * ObjectUtils.identityToString(appendable, Boolean.TRUE)  = appendable.append("java.lang.Boolean@7fa")
+     * 
+ * + * @param appendable the appendable to append to + * @param object the object to create a toString for + * @throws IOException if an I/O error occurs + * @since 3.2 + */ + public static void identityToString(final Appendable appendable, final Object object) throws IOException { + if (object == null) { + throw new NullPointerException("Cannot get the toString of a null identity"); + } + appendable.append(object.getClass().getName()) + .append('@') + .append(Integer.toHexString(System.identityHashCode(object))); + } + + /** + *

Appends the toString that would be produced by {@code Object} + * if a class did not override toString itself. {@code null} + * will throw a NullPointerException for either of the two parameters.

+ * + *
+     * ObjectUtils.identityToString(builder, "")            = builder.append("java.lang.String@1e23"
+     * ObjectUtils.identityToString(builder, Boolean.TRUE)  = builder.append("java.lang.Boolean@7fa"
+     * ObjectUtils.identityToString(builder, Boolean.TRUE)  = builder.append("java.lang.Boolean@7fa")
+     * 
+ * + * @param builder the builder to append to + * @param object the object to create a toString for + * @since 3.2 + */ + public static void identityToString(final StrBuilder builder, final Object object) { + if (object == null) { + throw new NullPointerException("Cannot get the toString of a null identity"); + } + builder.append(object.getClass().getName()) + .append('@') + .append(Integer.toHexString(System.identityHashCode(object))); + } + + /** + *

Appends the toString that would be produced by {@code Object} + * if a class did not override toString itself. {@code null} + * will throw a NullPointerException for either of the two parameters.

+ * + *
+     * ObjectUtils.identityToString(buf, "")            = buf.append("java.lang.String@1e23"
+     * ObjectUtils.identityToString(buf, Boolean.TRUE)  = buf.append("java.lang.Boolean@7fa"
+     * ObjectUtils.identityToString(buf, Boolean.TRUE)  = buf.append("java.lang.Boolean@7fa")
+     * 
+ * + * @param buffer the buffer to append to + * @param object the object to create a toString for + * @since 2.4 + */ + public static void identityToString(final StringBuffer buffer, final Object object) { + if (object == null) { + throw new NullPointerException("Cannot get the toString of a null identity"); + } + buffer.append(object.getClass().getName()) + .append('@') + .append(Integer.toHexString(System.identityHashCode(object))); + } + + /** + *

Appends the toString that would be produced by {@code Object} + * if a class did not override toString itself. {@code null} + * will throw a NullPointerException for either of the two parameters.

+ * + *
+     * ObjectUtils.identityToString(builder, "")            = builder.append("java.lang.String@1e23"
+     * ObjectUtils.identityToString(builder, Boolean.TRUE)  = builder.append("java.lang.Boolean@7fa"
+     * ObjectUtils.identityToString(builder, Boolean.TRUE)  = builder.append("java.lang.Boolean@7fa")
+     * 
+ * + * @param builder the builder to append to + * @param object the object to create a toString for + * @since 3.2 + */ + public static void identityToString(final StringBuilder builder, final Object object) { + if (object == null) { + throw new NullPointerException("Cannot get the toString of a null identity"); + } + builder.append(object.getClass().getName()) + .append('@') + .append(Integer.toHexString(System.identityHashCode(object))); + } + + // ToString + //----------------------------------------------------------------------- + /** + *

Gets the {@code toString} of an {@code Object} returning + * an empty string ("") if {@code null} input.

+ * + *
+     * ObjectUtils.toString(null)         = ""
+     * ObjectUtils.toString("")           = ""
+     * ObjectUtils.toString("bat")        = "bat"
+     * ObjectUtils.toString(Boolean.TRUE) = "true"
+     * 
+ * + * @see StringUtils#defaultString(String) + * @see String#valueOf(Object) + * @param obj the Object to {@code toString}, may be null + * @return the passed in Object's toString, or {@code ""} if {@code null} input + * @since 2.0 + * @deprecated this method has been replaced by {@code java.util.Objects.toString(Object)} in Java 7 and will be + * removed in future releases. Note however that said method will return "null" for null references, while this + * method returns and empty String. To preserve behavior use {@code java.util.Objects.toString(myObject, "")} + */ + @Deprecated +// ToString +// ----------------------------------------------------------------------- +/** + *

Gets the {@code toString} of an {@code Object} returning + * an empty string ("") if {@code null} input.

+ * + *
+ * ObjectUtils.toString(null)         = ""
+ * ObjectUtils.toString("")           = ""
+ * ObjectUtils.toString("bat")        = "bat"
+ * ObjectUtils.toString(Boolean.TRUE) = "true"
+ * 
+ * + * @see StringUtils#defaultString(String) + * @see String#valueOf(Object) + * @param obj + * the Object to {@code toString}, may be null + * @return the passed in Object's toString, or {@code ""} if {@code null} input + * @since 2.0 + * @deprecated this method has been replaced by {@code java.util.Objects.toString(Object)} in Java 7 and will be +removed in future releases. Note however that said method will return "null" for null references, while this +method returns and empty String. To preserve behavior use {@code java.util.Objects.toString(myObject, "")} + */ +public static java.lang.String toString(final java.lang.Object obj) { + return /* NPEX_NULL_EXP */ + obj.toString(); +} + + /** + *

Gets the {@code toString} of an {@code Object} returning + * a specified text if {@code null} input.

+ * + *
+     * ObjectUtils.toString(null, null)           = null
+     * ObjectUtils.toString(null, "null")         = "null"
+     * ObjectUtils.toString("", "null")           = ""
+     * ObjectUtils.toString("bat", "null")        = "bat"
+     * ObjectUtils.toString(Boolean.TRUE, "null") = "true"
+     * 
+ * + * @see StringUtils#defaultString(String,String) + * @see String#valueOf(Object) + * @param obj the Object to {@code toString}, may be null + * @param nullStr the String to return if {@code null} input, may be null + * @return the passed in Object's toString, or {@code nullStr} if {@code null} input + * @since 2.0 + * @deprecated this method has been replaced by {@code java.util.Objects.toString(Object, String)} in Java 7 and + * will be removed in future releases. + */ + @Deprecated + public static String toString(final Object obj, final String nullStr) { + return obj == null ? nullStr : obj.toString(); + } + + // Comparable + //----------------------------------------------------------------------- + /** + *

Null safe comparison of Comparables.

+ * + * @param type of the values processed by this method + * @param values the set of comparable values, may be null + * @return + *
    + *
  • If any objects are non-null and unequal, the lesser object. + *
  • If all objects are non-null and equal, the first. + *
  • If any of the comparables are null, the lesser of the non-null objects. + *
  • If all the comparables are null, null is returned. + *
+ */ + public static > T min(final T... values) { + T result = null; + if (values != null) { + for (final T value : values) { + if (compare(value, result, true) < 0) { + result = value; + } + } + } + return result; + } + + /** + *

Null safe comparison of Comparables.

+ * + * @param type of the values processed by this method + * @param values the set of comparable values, may be null + * @return + *
    + *
  • If any objects are non-null and unequal, the greater object. + *
  • If all objects are non-null and equal, the first. + *
  • If any of the comparables are null, the greater of the non-null objects. + *
  • If all the comparables are null, null is returned. + *
+ */ + public static > T max(final T... values) { + T result = null; + if (values != null) { + for (final T value : values) { + if (compare(value, result, false) > 0) { + result = value; + } + } + } + return result; + } + + /** + *

Null safe comparison of Comparables. + * {@code null} is assumed to be less than a non-{@code null} value.

+ * + * @param type of the values processed by this method + * @param c1 the first comparable, may be null + * @param c2 the second comparable, may be null + * @return a negative value if c1 < c2, zero if c1 = c2 + * and a positive value if c1 > c2 + */ + public static > int compare(final T c1, final T c2) { + return compare(c1, c2, false); + } + + /** + *

Null safe comparison of Comparables.

+ * + * @param type of the values processed by this method + * @param c1 the first comparable, may be null + * @param c2 the second comparable, may be null + * @param nullGreater if true {@code null} is considered greater + * than a non-{@code null} value or if false {@code null} is + * considered less than a Non-{@code null} value + * @return a negative value if c1 < c2, zero if c1 = c2 + * and a positive value if c1 > c2 + * @see java.util.Comparator#compare(Object, Object) + */ + public static > int compare(final T c1, final T c2, final boolean nullGreater) { + if (c1 == c2) { + return 0; + } else if (c1 == null) { + return nullGreater ? 1 : -1; + } else if (c2 == null) { + return nullGreater ? -1 : 1; + } + return c1.compareTo(c2); + } + + /** + * Find the "best guess" middle value among comparables. If there is an even + * number of total values, the lower of the two middle values will be returned. + * @param type of values processed by this method + * @param items to compare + * @return T at middle position + * @throws NullPointerException if items is {@code null} + * @throws IllegalArgumentException if items is empty or contains {@code null} values + * @since 3.0.1 + */ + public static > T median(final T... items) { + Validate.notEmpty(items); + Validate.noNullElements(items); + final TreeSet sort = new TreeSet(); + Collections.addAll(sort, items); + @SuppressWarnings("unchecked") //we know all items added were T instances + final + T result = (T) sort.toArray()[(sort.size() - 1) / 2]; + return result; + } + + /** + * Find the "best guess" middle value among comparables. If there is an even + * number of total values, the lower of the two middle values will be returned. + * @param type of values processed by this method + * @param comparator to use for comparisons + * @param items to compare + * @return T at middle position + * @throws NullPointerException if items or comparator is {@code null} + * @throws IllegalArgumentException if items is empty or contains {@code null} values + * @since 3.0.1 + */ + public static T median(final Comparator comparator, final T... items) { + Validate.notEmpty(items, "null/empty items"); + Validate.noNullElements(items); + Validate.notNull(comparator, "null comparator"); + final TreeSet sort = new TreeSet(comparator); + Collections.addAll(sort, items); + @SuppressWarnings("unchecked") //we know all items added were T instances + final + T result = (T) sort.toArray()[(sort.size() - 1) / 2]; + return result; + } + + // Mode + //----------------------------------------------------------------------- + /** + * Find the most frequently occurring item. + * + * @param type of values processed by this method + * @param items to check + * @return most populous T, {@code null} if non-unique or no items supplied + * @since 3.0.1 + */ + public static T mode(final T... items) { + if (ArrayUtils.isNotEmpty(items)) { + final HashMap occurrences = new HashMap(items.length); + for (final T t : items) { + final MutableInt count = occurrences.get(t); + if (count == null) { + occurrences.put(t, new MutableInt(1)); + } else { + count.increment(); + } + } + T result = null; + int max = 0; + for (final Map.Entry e : occurrences.entrySet()) { + final int cmp = e.getValue().intValue(); + if (cmp == max) { + result = null; + } else if (cmp > max) { + max = cmp; + result = e.getKey(); + } + } + return result; + } + return null; + } + + // cloning + //----------------------------------------------------------------------- + /** + *

Clone an object.

+ * + * @param the type of the object + * @param obj the object to clone, null returns null + * @return the clone if the object implements {@link Cloneable} otherwise {@code null} + * @throws CloneFailedException if the object is cloneable and the clone operation fails + * @since 3.0 + */ + public static T clone(final T obj) { + if (obj instanceof Cloneable) { + final Object result; + if (obj.getClass().isArray()) { + final Class componentType = obj.getClass().getComponentType(); + if (!componentType.isPrimitive()) { + result = ((Object[]) obj).clone(); + } else { + int length = Array.getLength(obj); + result = Array.newInstance(componentType, length); + while (length-- > 0) { + Array.set(result, length, Array.get(obj, length)); + } + } + } else { + try { + final Method clone = obj.getClass().getMethod("clone"); + result = clone.invoke(obj); + } catch (final NoSuchMethodException e) { + throw new CloneFailedException("Cloneable type " + + obj.getClass().getName() + + " has no clone method", e); + } catch (final IllegalAccessException e) { + throw new CloneFailedException("Cannot clone Cloneable type " + + obj.getClass().getName(), e); + } catch (final InvocationTargetException e) { + throw new CloneFailedException("Exception cloning Cloneable type " + + obj.getClass().getName(), e.getCause()); + } + } + @SuppressWarnings("unchecked") // OK because input is of type T + final T checked = (T) result; + return checked; + } + + return null; + } + + /** + *

Clone an object if possible.

+ * + *

This method is similar to {@link #clone(Object)}, but will return the provided + * instance as the return value instead of {@code null} if the instance + * is not cloneable. This is more convenient if the caller uses different + * implementations (e.g. of a service) and some of the implementations do not allow concurrent + * processing or have state. In such cases the implementation can simply provide a proper + * clone implementation and the caller's code does not have to change.

+ * + * @param the type of the object + * @param obj the object to clone, null returns null + * @return the clone if the object implements {@link Cloneable} otherwise the object itself + * @throws CloneFailedException if the object is cloneable and the clone operation fails + * @since 3.0 + */ + public static T cloneIfPossible(final T obj) { + final T clone = clone(obj); + return clone == null ? obj : clone; + } + + // Null + //----------------------------------------------------------------------- + /** + *

Class used as a null placeholder where {@code null} + * has another meaning.

+ * + *

For example, in a {@code HashMap} the + * {@link java.util.HashMap#get(java.lang.Object)} method returns + * {@code null} if the {@code Map} contains {@code null} or if there is + * no matching key. The {@code Null} placeholder can be used to distinguish + * between these two cases.

+ * + *

Another example is {@code Hashtable}, where {@code null} + * cannot be stored.

+ */ + public static class Null implements Serializable { + /** + * Required for serialization support. Declare serialization compatibility with Commons Lang 1.0 + * + * @see java.io.Serializable + */ + private static final long serialVersionUID = 7092611880189329093L; + + /** + * Restricted constructor - singleton. + */ + Null() { + super(); + } + + /** + *

Ensure singleton.

+ * + * @return the singleton value + */ + private Object readResolve() { + return ObjectUtils.NULL; + } + } + + + // Constants (LANG-816): + /* + These methods ensure constants are not inlined by javac. + For example, typically a developer might declare a constant like so: + + public final static int MAGIC_NUMBER = 5; + + Should a different jar file refer to this, and the MAGIC_NUMBER + is changed a later date (e.g., MAGIC_NUMBER = 6), the different jar + file will need to recompile itself. This is because javac + typically inlines the primitive or String constant directly into + the bytecode, and removes the reference to the MAGIC_NUMBER field. + + To help the other jar (so that it does not need to recompile + when constants are changed) the original developer can declare + their constant using one of the CONST() utility methods, instead: + + public final static int MAGIC_NUMBER = CONST(5); + */ + + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static boolean MAGIC_FLAG = ObjectUtils.CONST(true);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the boolean value to return + * @return the boolean v, unchanged + * @since 3.2 + */ + public static boolean CONST(final boolean v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static byte MAGIC_BYTE = ObjectUtils.CONST((byte) 127);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the byte value to return + * @return the byte v, unchanged + * @since 3.2 + */ + public static byte CONST(final byte v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static byte MAGIC_BYTE = ObjectUtils.CONST_BYTE(127);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the byte literal (as an int) value to return + * @throws IllegalArgumentException if the value passed to v + * is larger than a byte, that is, smaller than -128 or + * larger than 127. + * @return the byte v, unchanged + * @since 3.2 + */ + public static byte CONST_BYTE(final int v) throws IllegalArgumentException { + if (v < Byte.MIN_VALUE || v > Byte.MAX_VALUE) { + throw new IllegalArgumentException("Supplied value must be a valid byte literal between -128 and 127: [" + v + "]"); + } + return (byte) v; + } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static char MAGIC_CHAR = ObjectUtils.CONST('a');
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the char value to return + * @return the char v, unchanged + * @since 3.2 + */ + public static char CONST(final char v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static short MAGIC_SHORT = ObjectUtils.CONST((short) 123);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the short value to return + * @return the short v, unchanged + * @since 3.2 + */ + public static short CONST(final short v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static short MAGIC_SHORT = ObjectUtils.CONST_SHORT(127);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the short literal (as an int) value to return + * @throws IllegalArgumentException if the value passed to v + * is larger than a short, that is, smaller than -32768 or + * larger than 32767. + * @return the byte v, unchanged + * @since 3.2 + */ + public static short CONST_SHORT(final int v) throws IllegalArgumentException { + if (v < Short.MIN_VALUE || v > Short.MAX_VALUE) { + throw new IllegalArgumentException("Supplied value must be a valid byte literal between -32768 and 32767: [" + v + "]"); + } + return (short) v; + } + + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static int MAGIC_INT = ObjectUtils.CONST(123);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the int value to return + * @return the int v, unchanged + * @since 3.2 + */ + public static int CONST(final int v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static long MAGIC_LONG = ObjectUtils.CONST(123L);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the long value to return + * @return the long v, unchanged + * @since 3.2 + */ + public static long CONST(final long v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static float MAGIC_FLOAT = ObjectUtils.CONST(1.0f);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the float value to return + * @return the float v, unchanged + * @since 3.2 + */ + public static float CONST(final float v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static double MAGIC_DOUBLE = ObjectUtils.CONST(1.0);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the double value to return + * @return the double v, unchanged + * @since 3.2 + */ + public static double CONST(final double v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static String MAGIC_STRING = ObjectUtils.CONST("abc");
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param the Object type + * @param v the genericized Object value to return (typically a String). + * @return the genericized Object v, unchanged (typically a String). + * @since 3.2 + */ + public static T CONST(final T v) { return v; } + +} diff --git a/Java/commons-lang-ObjectUtils_457/metadata.json b/Java/commons-lang-ObjectUtils_457/metadata.json new file mode 100644 index 000000000..67b1fedb9 --- /dev/null +++ b/Java/commons-lang-ObjectUtils_457/metadata.json @@ -0,0 +1,21 @@ +{ + "language": "java", + "id": "commons-lang-ObjectUtils_457", + "buggyPath": ".", + "referencePath": null, + "buildCommand": "mvn package -V -B -Denforcer.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true -Drat.skip=true -Dlicense.skip=true -Dfindbugs.skip=true -Dgpg.skip=true -Dskip.npm=true -Dskip.gulp=true -Dskip.bower=true -Drat.numUnapprovedLicenses=100 -DskipTests=true -DskipITs=true -Dtest=None -DfailIfNoTests=false", + "testCommand": "mvn test -V -B -Denforcer.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true -Drat.skip=true -Dlicense.skip=true -Dfindbugs.skip=true -Dgpg.skip=true -Dskip.npm=true -Dskip.gulp=true -Dskip.bower=true -Drat.numUnapprovedLicenses=100", + "categories": [ + "safety", + "npe" + ], + "npe": { + "filepath": "src/main/java/org/apache/commons/lang3/ObjectUtils.java", + "line": 481, + "npe_method": "toString", + "deref_field": "obj", + "npe_class": "ObjectUtils", + "repo": "commons-lang", + "bug_id": "ObjectUtils_457" + } +} diff --git a/Java/commons-lang-ObjectUtils_457/npe.json b/Java/commons-lang-ObjectUtils_457/npe.json new file mode 100644 index 000000000..99a6cd164 --- /dev/null +++ b/Java/commons-lang-ObjectUtils_457/npe.json @@ -0,0 +1,7 @@ +{ + "filepath": "src/main/java/org/apache/commons/lang3/ObjectUtils.java", + "line": 481, + "npe_method": "toString", + "deref_field": "obj", + "npe_class": "ObjectUtils" +} \ No newline at end of file diff --git a/Java/commons-lang-ObjectUtils_483/Dockerfile b/Java/commons-lang-ObjectUtils_483/Dockerfile new file mode 100644 index 000000000..7b7fbe349 --- /dev/null +++ b/Java/commons-lang-ObjectUtils_483/Dockerfile @@ -0,0 +1,18 @@ +FROM ghcr.io/kupl/starlab-benchmarks/java-base:commons-lang + +ENV TZ=Asia/Seoul + +COPY ./metadata.json . +COPY ./npe.json . +COPY ./buggy.java /tmp/buggy.java +RUN export BUGGY_PATH=$(cat metadata.json | jq -r ".npe.filepath") \ + && export BUGGY_LINE=$(cat metadata.json | jq -r ".npe.line") \ + && export BUGGY_MTHD=$(cat metadata.json | jq -r ".npe.npe_method") \ + && mv /tmp/buggy.java $BUGGY_PATH \ + && echo "[{\"filepath\": \"$BUGGY_PATH\", \"line\": $BUGGY_LINE, \"method_name\": \"$BUGGY_MTHD\"}]" | jq . > traces.json + +RUN git init . && git add -A + +RUN $(cat metadata.json | jq -r ".buildCommand") + +RUN $(cat metadata.json | jq -r ".testCommand"); if [ $? -eq 0 ]; then exit 1; fi diff --git a/Java/commons-lang-ObjectUtils_483/buggy.java b/Java/commons-lang-ObjectUtils_483/buggy.java new file mode 100644 index 000000000..f432aabbe --- /dev/null +++ b/Java/commons-lang-ObjectUtils_483/buggy.java @@ -0,0 +1,1040 @@ +/* + * 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.Serializable; +import java.lang.reflect.Array; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.Map; +import java.util.TreeSet; + +import org.apache.commons.lang3.exception.CloneFailedException; +import org.apache.commons.lang3.mutable.MutableInt; +import org.apache.commons.lang3.text.StrBuilder; + +/** + *

Operations on {@code Object}.

+ * + *

This class tries to handle {@code null} input gracefully. + * An exception will generally not be thrown for a {@code null} input. + * Each method documents its behaviour in more detail.

+ * + *

#ThreadSafe#

+ * @since 1.0 + */ +//@Immutable +public class ObjectUtils { + + /** + *

Singleton used as a {@code null} placeholder where + * {@code null} has another meaning.

+ * + *

For example, in a {@code HashMap} the + * {@link java.util.HashMap#get(java.lang.Object)} method returns + * {@code null} if the {@code Map} contains {@code null} or if there + * is no matching key. The {@code Null} placeholder can be used to + * distinguish between these two cases.

+ * + *

Another example is {@code Hashtable}, where {@code null} + * cannot be stored.

+ * + *

This instance is Serializable.

+ */ + public static final Null NULL = new Null(); + + /** + *

{@code ObjectUtils} instances should NOT be constructed in + * standard programming. Instead, the static methods on the class should + * be used, such as {@code ObjectUtils.defaultIfNull("a","b");}.

+ * + *

This constructor is public to permit tools that require a JavaBean + * instance to operate.

+ */ + public ObjectUtils() { + super(); + } + + // Defaulting + //----------------------------------------------------------------------- + /** + *

Returns a default value if the object passed is {@code null}.

+ * + *
+     * ObjectUtils.defaultIfNull(null, null)      = null
+     * ObjectUtils.defaultIfNull(null, "")        = ""
+     * ObjectUtils.defaultIfNull(null, "zz")      = "zz"
+     * ObjectUtils.defaultIfNull("abc", *)        = "abc"
+     * ObjectUtils.defaultIfNull(Boolean.TRUE, *) = Boolean.TRUE
+     * 
+ * + * @param the type of the object + * @param object the {@code Object} to test, may be {@code null} + * @param defaultValue the default value to return, may be {@code null} + * @return {@code object} if it is not {@code null}, defaultValue otherwise + */ + public static T defaultIfNull(final T object, final T defaultValue) { + return object != null ? object : defaultValue; + } + + /** + *

Returns the first value in the array which is not {@code null}. + * If all the values are {@code null} or the array is {@code null} + * or empty then {@code null} is returned.

+ * + *
+     * ObjectUtils.firstNonNull(null, null)      = null
+     * ObjectUtils.firstNonNull(null, "")        = ""
+     * ObjectUtils.firstNonNull(null, null, "")  = ""
+     * ObjectUtils.firstNonNull(null, "zz")      = "zz"
+     * ObjectUtils.firstNonNull("abc", *)        = "abc"
+     * ObjectUtils.firstNonNull(null, "xyz", *)  = "xyz"
+     * ObjectUtils.firstNonNull(Boolean.TRUE, *) = Boolean.TRUE
+     * ObjectUtils.firstNonNull()                = null
+     * 
+ * + * @param the component type of the array + * @param values the values to test, may be {@code null} or empty + * @return the first value from {@code values} which is not {@code null}, + * or {@code null} if there are no non-null values + * @since 3.0 + */ + public static T firstNonNull(final T... values) { + if (values != null) { + for (final T val : values) { + if (val != null) { + return val; + } + } + } + return null; + } + + /** + * Checks if any value in the given array is not {@code null}. + * + *

+ * If all the values are {@code null} or the array is {@code null} + * or empty then {@code false} is returned. Otherwise {@code true} is returned. + *

+ * + *
+     * ObjectUtils.anyNotNull(*)                = true
+     * ObjectUtils.anyNotNull(*, null)          = true
+     * ObjectUtils.anyNotNull(null, *)          = true
+     * ObjectUtils.anyNotNull(null, null, *, *) = true
+     * ObjectUtils.anyNotNull(null)             = false
+     * ObjectUtils.anyNotNull(null, null)       = false
+     * 
+ * + * @param values the values to test, may be {@code null} or empty + * @return {@code true} if there is at least one non-null value in the array, + * {@code false} if all values in the array are {@code null}s. + * If the array is {@code null} or empty {@code false} is also returned. + * @since 3.5 + */ + public static boolean anyNotNull(final Object... values) { + return firstNonNull(values) != null; + } + + /** + * Checks if all values in the array are not {@code nulls}. + * + *

+ * If any value is {@code null} or the array is {@code null} then + * {@code false} is returned. If all elements in array are not + * {@code null} or the array is empty (contains no elements) {@code true} + * is returned. + *

+ * + *
+     * ObjectUtils.allNotNull(*)             = true
+     * ObjectUtils.allNotNull(*, *)          = true
+     * ObjectUtils.allNotNull(null)          = false
+     * ObjectUtils.allNotNull(null, null)    = false
+     * ObjectUtils.allNotNull(null, *)       = false
+     * ObjectUtils.allNotNull(*, null)       = false
+     * ObjectUtils.allNotNull(*, *, null, *) = false
+     * 
+ * + * @param values the values to test, may be {@code null} or empty + * @return {@code false} if there is at least one {@code null} value in the array or the array is {@code null}, + * {@code true} if all values in the array are not {@code null}s or array contains no elements. + * @since 3.5 + */ + public static boolean allNotNull(final Object... values) { + if (values == null) { + return false; + } + + for (final Object val : values) { + if (val == null) { + return false; + } + } + + return true; + } + + // Null-safe equals/hashCode + //----------------------------------------------------------------------- + /** + *

Compares two objects for equality, where either one or both + * objects may be {@code null}.

+ * + *
+     * ObjectUtils.equals(null, null)                  = true
+     * ObjectUtils.equals(null, "")                    = false
+     * ObjectUtils.equals("", null)                    = false
+     * ObjectUtils.equals("", "")                      = true
+     * ObjectUtils.equals(Boolean.TRUE, null)          = false
+     * ObjectUtils.equals(Boolean.TRUE, "true")        = false
+     * ObjectUtils.equals(Boolean.TRUE, Boolean.TRUE)  = true
+     * ObjectUtils.equals(Boolean.TRUE, Boolean.FALSE) = false
+     * 
+ * + * @param object1 the first object, may be {@code null} + * @param object2 the second object, may be {@code null} + * @return {@code true} if the values of both objects are the same + * @deprecated this method has been replaced by {@code java.util.Objects.equals(Object, Object)} in Java 7 and will + * be removed from future releases. + */ + @Deprecated + public static boolean equals(final Object object1, final Object object2) { + if (object1 == object2) { + return true; + } + if (object1 == null || object2 == null) { + return false; + } + return object1.equals(object2); + } + + /** + *

Compares two objects for inequality, where either one or both + * objects may be {@code null}.

+ * + *
+     * ObjectUtils.notEqual(null, null)                  = false
+     * ObjectUtils.notEqual(null, "")                    = true
+     * ObjectUtils.notEqual("", null)                    = true
+     * ObjectUtils.notEqual("", "")                      = false
+     * ObjectUtils.notEqual(Boolean.TRUE, null)          = true
+     * ObjectUtils.notEqual(Boolean.TRUE, "true")        = true
+     * ObjectUtils.notEqual(Boolean.TRUE, Boolean.TRUE)  = false
+     * ObjectUtils.notEqual(Boolean.TRUE, Boolean.FALSE) = true
+     * 
+ * + * @param object1 the first object, may be {@code null} + * @param object2 the second object, may be {@code null} + * @return {@code false} if the values of both objects are the same + */ + public static boolean notEqual(final Object object1, final Object object2) { + return ObjectUtils.equals(object1, object2) == false; + } + + /** + *

Gets the hash code of an object returning zero when the + * object is {@code null}.

+ * + *
+     * ObjectUtils.hashCode(null)   = 0
+     * ObjectUtils.hashCode(obj)    = obj.hashCode()
+     * 
+ * + * @param obj the object to obtain the hash code of, may be {@code null} + * @return the hash code of the object, or zero if null + * @since 2.1 + * @deprecated this method has been replaced by {@code java.util.Objects.hashCode(Object)} in Java 7 and will be + * removed in future releases + */ + @Deprecated + public static int hashCode(final Object obj) { + // hashCode(Object) retained for performance, as hash code is often critical + return obj == null ? 0 : obj.hashCode(); + } + + /** + *

Gets the hash code for multiple objects.

+ * + *

This allows a hash code to be rapidly calculated for a number of objects. + * The hash code for a single object is the not same as {@link #hashCode(Object)}. + * The hash code for multiple objects is the same as that calculated by an + * {@code ArrayList} containing the specified objects.

+ * + *
+     * ObjectUtils.hashCodeMulti()                 = 1
+     * ObjectUtils.hashCodeMulti((Object[]) null)  = 1
+     * ObjectUtils.hashCodeMulti(a)                = 31 + a.hashCode()
+     * ObjectUtils.hashCodeMulti(a,b)              = (31 + a.hashCode()) * 31 + b.hashCode()
+     * ObjectUtils.hashCodeMulti(a,b,c)            = ((31 + a.hashCode()) * 31 + b.hashCode()) * 31 + c.hashCode()
+     * 
+ * + * @param objects the objects to obtain the hash code of, may be {@code null} + * @return the hash code of the objects, or zero if null + * @since 3.0 + * @deprecated this method has been replaced by {@code java.util.Objects.hash(Object...)} in Java 7 and will be + * removed in future releases. + */ + @Deprecated + public static int hashCodeMulti(final Object... objects) { + int hash = 1; + if (objects != null) { + for (final Object object : objects) { + final int tmpHash = ObjectUtils.hashCode(object); + hash = hash * 31 + tmpHash; + } + } + return hash; + } + + // Identity ToString + //----------------------------------------------------------------------- + /** + *

Gets the toString that would be produced by {@code Object} + * if a class did not override toString itself. {@code null} + * will return {@code null}.

+ * + *
+     * ObjectUtils.identityToString(null)         = null
+     * ObjectUtils.identityToString("")           = "java.lang.String@1e23"
+     * ObjectUtils.identityToString(Boolean.TRUE) = "java.lang.Boolean@7fa"
+     * 
+ * + * @param object the object to create a toString for, may be + * {@code null} + * @return the default toString text, or {@code null} if + * {@code null} passed in + */ + public static String identityToString(final Object object) { + if (object == null) { + return null; + } + final StringBuilder builder = new StringBuilder(); + identityToString(builder, object); + return builder.toString(); + } + + /** + *

Appends the toString that would be produced by {@code Object} + * if a class did not override toString itself. {@code null} + * will throw a NullPointerException for either of the two parameters.

+ * + *
+     * ObjectUtils.identityToString(appendable, "")            = appendable.append("java.lang.String@1e23"
+     * ObjectUtils.identityToString(appendable, Boolean.TRUE)  = appendable.append("java.lang.Boolean@7fa"
+     * ObjectUtils.identityToString(appendable, Boolean.TRUE)  = appendable.append("java.lang.Boolean@7fa")
+     * 
+ * + * @param appendable the appendable to append to + * @param object the object to create a toString for + * @throws IOException if an I/O error occurs + * @since 3.2 + */ + public static void identityToString(final Appendable appendable, final Object object) throws IOException { + if (object == null) { + throw new NullPointerException("Cannot get the toString of a null identity"); + } + appendable.append(object.getClass().getName()) + .append('@') + .append(Integer.toHexString(System.identityHashCode(object))); + } + + /** + *

Appends the toString that would be produced by {@code Object} + * if a class did not override toString itself. {@code null} + * will throw a NullPointerException for either of the two parameters.

+ * + *
+     * ObjectUtils.identityToString(builder, "")            = builder.append("java.lang.String@1e23"
+     * ObjectUtils.identityToString(builder, Boolean.TRUE)  = builder.append("java.lang.Boolean@7fa"
+     * ObjectUtils.identityToString(builder, Boolean.TRUE)  = builder.append("java.lang.Boolean@7fa")
+     * 
+ * + * @param builder the builder to append to + * @param object the object to create a toString for + * @since 3.2 + */ + public static void identityToString(final StrBuilder builder, final Object object) { + if (object == null) { + throw new NullPointerException("Cannot get the toString of a null identity"); + } + builder.append(object.getClass().getName()) + .append('@') + .append(Integer.toHexString(System.identityHashCode(object))); + } + + /** + *

Appends the toString that would be produced by {@code Object} + * if a class did not override toString itself. {@code null} + * will throw a NullPointerException for either of the two parameters.

+ * + *
+     * ObjectUtils.identityToString(buf, "")            = buf.append("java.lang.String@1e23"
+     * ObjectUtils.identityToString(buf, Boolean.TRUE)  = buf.append("java.lang.Boolean@7fa"
+     * ObjectUtils.identityToString(buf, Boolean.TRUE)  = buf.append("java.lang.Boolean@7fa")
+     * 
+ * + * @param buffer the buffer to append to + * @param object the object to create a toString for + * @since 2.4 + */ + public static void identityToString(final StringBuffer buffer, final Object object) { + if (object == null) { + throw new NullPointerException("Cannot get the toString of a null identity"); + } + buffer.append(object.getClass().getName()) + .append('@') + .append(Integer.toHexString(System.identityHashCode(object))); + } + + /** + *

Appends the toString that would be produced by {@code Object} + * if a class did not override toString itself. {@code null} + * will throw a NullPointerException for either of the two parameters.

+ * + *
+     * ObjectUtils.identityToString(builder, "")            = builder.append("java.lang.String@1e23"
+     * ObjectUtils.identityToString(builder, Boolean.TRUE)  = builder.append("java.lang.Boolean@7fa"
+     * ObjectUtils.identityToString(builder, Boolean.TRUE)  = builder.append("java.lang.Boolean@7fa")
+     * 
+ * + * @param builder the builder to append to + * @param object the object to create a toString for + * @since 3.2 + */ + public static void identityToString(final StringBuilder builder, final Object object) { + if (object == null) { + throw new NullPointerException("Cannot get the toString of a null identity"); + } + builder.append(object.getClass().getName()) + .append('@') + .append(Integer.toHexString(System.identityHashCode(object))); + } + + // ToString + //----------------------------------------------------------------------- + /** + *

Gets the {@code toString} of an {@code Object} returning + * an empty string ("") if {@code null} input.

+ * + *
+     * ObjectUtils.toString(null)         = ""
+     * ObjectUtils.toString("")           = ""
+     * ObjectUtils.toString("bat")        = "bat"
+     * ObjectUtils.toString(Boolean.TRUE) = "true"
+     * 
+ * + * @see StringUtils#defaultString(String) + * @see String#valueOf(Object) + * @param obj the Object to {@code toString}, may be null + * @return the passed in Object's toString, or {@code ""} if {@code null} input + * @since 2.0 + * @deprecated this method has been replaced by {@code java.util.Objects.toString(Object)} in Java 7 and will be + * removed in future releases. Note however that said method will return "null" for null references, while this + * method returns and empty String. To preserve behavior use {@code java.util.Objects.toString(myObject, "")} + */ + @Deprecated + public static String toString(final Object obj) { + return obj == null ? StringUtils.EMPTY : obj.toString(); + } + + /** + *

Gets the {@code toString} of an {@code Object} returning + * a specified text if {@code null} input.

+ * + *
+     * ObjectUtils.toString(null, null)           = null
+     * ObjectUtils.toString(null, "null")         = "null"
+     * ObjectUtils.toString("", "null")           = ""
+     * ObjectUtils.toString("bat", "null")        = "bat"
+     * ObjectUtils.toString(Boolean.TRUE, "null") = "true"
+     * 
+ * + * @see StringUtils#defaultString(String,String) + * @see String#valueOf(Object) + * @param obj the Object to {@code toString}, may be null + * @param nullStr the String to return if {@code null} input, may be null + * @return the passed in Object's toString, or {@code nullStr} if {@code null} input + * @since 2.0 + * @deprecated this method has been replaced by {@code java.util.Objects.toString(Object, String)} in Java 7 and + * will be removed in future releases. + */ + @Deprecated +/** + *

Gets the {@code toString} of an {@code Object} returning + * a specified text if {@code null} input.

+ * + *
+ * ObjectUtils.toString(null, null)           = null
+ * ObjectUtils.toString(null, "null")         = "null"
+ * ObjectUtils.toString("", "null")           = ""
+ * ObjectUtils.toString("bat", "null")        = "bat"
+ * ObjectUtils.toString(Boolean.TRUE, "null") = "true"
+ * 
+ * + * @see StringUtils#defaultString(String,String) + * @see String#valueOf(Object) + * @param obj + * the Object to {@code toString}, may be null + * @param nullStr + * the String to return if {@code null} input, may be null + * @return the passed in Object's toString, or {@code nullStr} if {@code null} input + * @since 2.0 + * @deprecated this method has been replaced by {@code java.util.Objects.toString(Object, String)} in Java 7 and +will be removed in future releases. + */ +public static java.lang.String toString(final java.lang.Object obj, final java.lang.String nullStr) { + return /* NPEX_NULL_EXP */ + obj.toString(); +} + + // Comparable + //----------------------------------------------------------------------- + /** + *

Null safe comparison of Comparables.

+ * + * @param type of the values processed by this method + * @param values the set of comparable values, may be null + * @return + *
    + *
  • If any objects are non-null and unequal, the lesser object. + *
  • If all objects are non-null and equal, the first. + *
  • If any of the comparables are null, the lesser of the non-null objects. + *
  • If all the comparables are null, null is returned. + *
+ */ + public static > T min(final T... values) { + T result = null; + if (values != null) { + for (final T value : values) { + if (compare(value, result, true) < 0) { + result = value; + } + } + } + return result; + } + + /** + *

Null safe comparison of Comparables.

+ * + * @param type of the values processed by this method + * @param values the set of comparable values, may be null + * @return + *
    + *
  • If any objects are non-null and unequal, the greater object. + *
  • If all objects are non-null and equal, the first. + *
  • If any of the comparables are null, the greater of the non-null objects. + *
  • If all the comparables are null, null is returned. + *
+ */ + public static > T max(final T... values) { + T result = null; + if (values != null) { + for (final T value : values) { + if (compare(value, result, false) > 0) { + result = value; + } + } + } + return result; + } + + /** + *

Null safe comparison of Comparables. + * {@code null} is assumed to be less than a non-{@code null} value.

+ * + * @param type of the values processed by this method + * @param c1 the first comparable, may be null + * @param c2 the second comparable, may be null + * @return a negative value if c1 < c2, zero if c1 = c2 + * and a positive value if c1 > c2 + */ + public static > int compare(final T c1, final T c2) { + return compare(c1, c2, false); + } + + /** + *

Null safe comparison of Comparables.

+ * + * @param type of the values processed by this method + * @param c1 the first comparable, may be null + * @param c2 the second comparable, may be null + * @param nullGreater if true {@code null} is considered greater + * than a non-{@code null} value or if false {@code null} is + * considered less than a Non-{@code null} value + * @return a negative value if c1 < c2, zero if c1 = c2 + * and a positive value if c1 > c2 + * @see java.util.Comparator#compare(Object, Object) + */ + public static > int compare(final T c1, final T c2, final boolean nullGreater) { + if (c1 == c2) { + return 0; + } else if (c1 == null) { + return nullGreater ? 1 : -1; + } else if (c2 == null) { + return nullGreater ? -1 : 1; + } + return c1.compareTo(c2); + } + + /** + * Find the "best guess" middle value among comparables. If there is an even + * number of total values, the lower of the two middle values will be returned. + * @param type of values processed by this method + * @param items to compare + * @return T at middle position + * @throws NullPointerException if items is {@code null} + * @throws IllegalArgumentException if items is empty or contains {@code null} values + * @since 3.0.1 + */ + public static > T median(final T... items) { + Validate.notEmpty(items); + Validate.noNullElements(items); + final TreeSet sort = new TreeSet(); + Collections.addAll(sort, items); + @SuppressWarnings("unchecked") //we know all items added were T instances + final + T result = (T) sort.toArray()[(sort.size() - 1) / 2]; + return result; + } + + /** + * Find the "best guess" middle value among comparables. If there is an even + * number of total values, the lower of the two middle values will be returned. + * @param type of values processed by this method + * @param comparator to use for comparisons + * @param items to compare + * @return T at middle position + * @throws NullPointerException if items or comparator is {@code null} + * @throws IllegalArgumentException if items is empty or contains {@code null} values + * @since 3.0.1 + */ + public static T median(final Comparator comparator, final T... items) { + Validate.notEmpty(items, "null/empty items"); + Validate.noNullElements(items); + Validate.notNull(comparator, "null comparator"); + final TreeSet sort = new TreeSet(comparator); + Collections.addAll(sort, items); + @SuppressWarnings("unchecked") //we know all items added were T instances + final + T result = (T) sort.toArray()[(sort.size() - 1) / 2]; + return result; + } + + // Mode + //----------------------------------------------------------------------- + /** + * Find the most frequently occurring item. + * + * @param type of values processed by this method + * @param items to check + * @return most populous T, {@code null} if non-unique or no items supplied + * @since 3.0.1 + */ + public static T mode(final T... items) { + if (ArrayUtils.isNotEmpty(items)) { + final HashMap occurrences = new HashMap(items.length); + for (final T t : items) { + final MutableInt count = occurrences.get(t); + if (count == null) { + occurrences.put(t, new MutableInt(1)); + } else { + count.increment(); + } + } + T result = null; + int max = 0; + for (final Map.Entry e : occurrences.entrySet()) { + final int cmp = e.getValue().intValue(); + if (cmp == max) { + result = null; + } else if (cmp > max) { + max = cmp; + result = e.getKey(); + } + } + return result; + } + return null; + } + + // cloning + //----------------------------------------------------------------------- + /** + *

Clone an object.

+ * + * @param the type of the object + * @param obj the object to clone, null returns null + * @return the clone if the object implements {@link Cloneable} otherwise {@code null} + * @throws CloneFailedException if the object is cloneable and the clone operation fails + * @since 3.0 + */ + public static T clone(final T obj) { + if (obj instanceof Cloneable) { + final Object result; + if (obj.getClass().isArray()) { + final Class componentType = obj.getClass().getComponentType(); + if (!componentType.isPrimitive()) { + result = ((Object[]) obj).clone(); + } else { + int length = Array.getLength(obj); + result = Array.newInstance(componentType, length); + while (length-- > 0) { + Array.set(result, length, Array.get(obj, length)); + } + } + } else { + try { + final Method clone = obj.getClass().getMethod("clone"); + result = clone.invoke(obj); + } catch (final NoSuchMethodException e) { + throw new CloneFailedException("Cloneable type " + + obj.getClass().getName() + + " has no clone method", e); + } catch (final IllegalAccessException e) { + throw new CloneFailedException("Cannot clone Cloneable type " + + obj.getClass().getName(), e); + } catch (final InvocationTargetException e) { + throw new CloneFailedException("Exception cloning Cloneable type " + + obj.getClass().getName(), e.getCause()); + } + } + @SuppressWarnings("unchecked") // OK because input is of type T + final T checked = (T) result; + return checked; + } + + return null; + } + + /** + *

Clone an object if possible.

+ * + *

This method is similar to {@link #clone(Object)}, but will return the provided + * instance as the return value instead of {@code null} if the instance + * is not cloneable. This is more convenient if the caller uses different + * implementations (e.g. of a service) and some of the implementations do not allow concurrent + * processing or have state. In such cases the implementation can simply provide a proper + * clone implementation and the caller's code does not have to change.

+ * + * @param the type of the object + * @param obj the object to clone, null returns null + * @return the clone if the object implements {@link Cloneable} otherwise the object itself + * @throws CloneFailedException if the object is cloneable and the clone operation fails + * @since 3.0 + */ + public static T cloneIfPossible(final T obj) { + final T clone = clone(obj); + return clone == null ? obj : clone; + } + + // Null + //----------------------------------------------------------------------- + /** + *

Class used as a null placeholder where {@code null} + * has another meaning.

+ * + *

For example, in a {@code HashMap} the + * {@link java.util.HashMap#get(java.lang.Object)} method returns + * {@code null} if the {@code Map} contains {@code null} or if there is + * no matching key. The {@code Null} placeholder can be used to distinguish + * between these two cases.

+ * + *

Another example is {@code Hashtable}, where {@code null} + * cannot be stored.

+ */ + public static class Null implements Serializable { + /** + * Required for serialization support. Declare serialization compatibility with Commons Lang 1.0 + * + * @see java.io.Serializable + */ + private static final long serialVersionUID = 7092611880189329093L; + + /** + * Restricted constructor - singleton. + */ + Null() { + super(); + } + + /** + *

Ensure singleton.

+ * + * @return the singleton value + */ + private Object readResolve() { + return ObjectUtils.NULL; + } + } + + + // Constants (LANG-816): + /* + These methods ensure constants are not inlined by javac. + For example, typically a developer might declare a constant like so: + + public final static int MAGIC_NUMBER = 5; + + Should a different jar file refer to this, and the MAGIC_NUMBER + is changed a later date (e.g., MAGIC_NUMBER = 6), the different jar + file will need to recompile itself. This is because javac + typically inlines the primitive or String constant directly into + the bytecode, and removes the reference to the MAGIC_NUMBER field. + + To help the other jar (so that it does not need to recompile + when constants are changed) the original developer can declare + their constant using one of the CONST() utility methods, instead: + + public final static int MAGIC_NUMBER = CONST(5); + */ + + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static boolean MAGIC_FLAG = ObjectUtils.CONST(true);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the boolean value to return + * @return the boolean v, unchanged + * @since 3.2 + */ + public static boolean CONST(final boolean v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static byte MAGIC_BYTE = ObjectUtils.CONST((byte) 127);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the byte value to return + * @return the byte v, unchanged + * @since 3.2 + */ + public static byte CONST(final byte v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static byte MAGIC_BYTE = ObjectUtils.CONST_BYTE(127);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the byte literal (as an int) value to return + * @throws IllegalArgumentException if the value passed to v + * is larger than a byte, that is, smaller than -128 or + * larger than 127. + * @return the byte v, unchanged + * @since 3.2 + */ + public static byte CONST_BYTE(final int v) throws IllegalArgumentException { + if (v < Byte.MIN_VALUE || v > Byte.MAX_VALUE) { + throw new IllegalArgumentException("Supplied value must be a valid byte literal between -128 and 127: [" + v + "]"); + } + return (byte) v; + } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static char MAGIC_CHAR = ObjectUtils.CONST('a');
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the char value to return + * @return the char v, unchanged + * @since 3.2 + */ + public static char CONST(final char v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static short MAGIC_SHORT = ObjectUtils.CONST((short) 123);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the short value to return + * @return the short v, unchanged + * @since 3.2 + */ + public static short CONST(final short v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static short MAGIC_SHORT = ObjectUtils.CONST_SHORT(127);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the short literal (as an int) value to return + * @throws IllegalArgumentException if the value passed to v + * is larger than a short, that is, smaller than -32768 or + * larger than 32767. + * @return the byte v, unchanged + * @since 3.2 + */ + public static short CONST_SHORT(final int v) throws IllegalArgumentException { + if (v < Short.MIN_VALUE || v > Short.MAX_VALUE) { + throw new IllegalArgumentException("Supplied value must be a valid byte literal between -32768 and 32767: [" + v + "]"); + } + return (short) v; + } + + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static int MAGIC_INT = ObjectUtils.CONST(123);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the int value to return + * @return the int v, unchanged + * @since 3.2 + */ + public static int CONST(final int v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static long MAGIC_LONG = ObjectUtils.CONST(123L);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the long value to return + * @return the long v, unchanged + * @since 3.2 + */ + public static long CONST(final long v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static float MAGIC_FLOAT = ObjectUtils.CONST(1.0f);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the float value to return + * @return the float v, unchanged + * @since 3.2 + */ + public static float CONST(final float v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static double MAGIC_DOUBLE = ObjectUtils.CONST(1.0);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the double value to return + * @return the double v, unchanged + * @since 3.2 + */ + public static double CONST(final double v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static String MAGIC_STRING = ObjectUtils.CONST("abc");
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param the Object type + * @param v the genericized Object value to return (typically a String). + * @return the genericized Object v, unchanged (typically a String). + * @since 3.2 + */ + public static T CONST(final T v) { return v; } + +} diff --git a/Java/commons-lang-ObjectUtils_483/metadata.json b/Java/commons-lang-ObjectUtils_483/metadata.json new file mode 100644 index 000000000..516e94023 --- /dev/null +++ b/Java/commons-lang-ObjectUtils_483/metadata.json @@ -0,0 +1,21 @@ +{ + "language": "java", + "id": "commons-lang-ObjectUtils_483", + "buggyPath": ".", + "referencePath": null, + "buildCommand": "mvn package -V -B -Denforcer.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true -Drat.skip=true -Dlicense.skip=true -Dfindbugs.skip=true -Dgpg.skip=true -Dskip.npm=true -Dskip.gulp=true -Dskip.bower=true -Drat.numUnapprovedLicenses=100 -DskipTests=true -DskipITs=true -Dtest=None -DfailIfNoTests=false", + "testCommand": "mvn test -V -B -Denforcer.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true -Drat.skip=true -Dlicense.skip=true -Dfindbugs.skip=true -Dgpg.skip=true -Dskip.npm=true -Dskip.gulp=true -Dskip.bower=true -Drat.numUnapprovedLicenses=100", + "categories": [ + "safety", + "npe" + ], + "npe": { + "filepath": "src/main/java/org/apache/commons/lang3/ObjectUtils.java", + "line": 507, + "npe_method": "toString", + "deref_field": "obj", + "npe_class": "ObjectUtils", + "repo": "commons-lang", + "bug_id": "ObjectUtils_483" + } +} diff --git a/Java/commons-lang-ObjectUtils_483/npe.json b/Java/commons-lang-ObjectUtils_483/npe.json new file mode 100644 index 000000000..fcf9b46f2 --- /dev/null +++ b/Java/commons-lang-ObjectUtils_483/npe.json @@ -0,0 +1,7 @@ +{ + "filepath": "src/main/java/org/apache/commons/lang3/ObjectUtils.java", + "line": 507, + "npe_method": "toString", + "deref_field": "obj", + "npe_class": "ObjectUtils" +} \ No newline at end of file diff --git a/Java/commons-lang-ObjectUtils_503/Dockerfile b/Java/commons-lang-ObjectUtils_503/Dockerfile new file mode 100644 index 000000000..7b7fbe349 --- /dev/null +++ b/Java/commons-lang-ObjectUtils_503/Dockerfile @@ -0,0 +1,18 @@ +FROM ghcr.io/kupl/starlab-benchmarks/java-base:commons-lang + +ENV TZ=Asia/Seoul + +COPY ./metadata.json . +COPY ./npe.json . +COPY ./buggy.java /tmp/buggy.java +RUN export BUGGY_PATH=$(cat metadata.json | jq -r ".npe.filepath") \ + && export BUGGY_LINE=$(cat metadata.json | jq -r ".npe.line") \ + && export BUGGY_MTHD=$(cat metadata.json | jq -r ".npe.npe_method") \ + && mv /tmp/buggy.java $BUGGY_PATH \ + && echo "[{\"filepath\": \"$BUGGY_PATH\", \"line\": $BUGGY_LINE, \"method_name\": \"$BUGGY_MTHD\"}]" | jq . > traces.json + +RUN git init . && git add -A + +RUN $(cat metadata.json | jq -r ".buildCommand") + +RUN $(cat metadata.json | jq -r ".testCommand"); if [ $? -eq 0 ]; then exit 1; fi diff --git a/Java/commons-lang-ObjectUtils_503/buggy.java b/Java/commons-lang-ObjectUtils_503/buggy.java new file mode 100644 index 000000000..a88cd6279 --- /dev/null +++ b/Java/commons-lang-ObjectUtils_503/buggy.java @@ -0,0 +1,1033 @@ +/* + * 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.Serializable; +import java.lang.reflect.Array; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.Map; +import java.util.TreeSet; + +import org.apache.commons.lang3.exception.CloneFailedException; +import org.apache.commons.lang3.mutable.MutableInt; +import org.apache.commons.lang3.text.StrBuilder; + +/** + *

Operations on {@code Object}.

+ * + *

This class tries to handle {@code null} input gracefully. + * An exception will generally not be thrown for a {@code null} input. + * Each method documents its behaviour in more detail.

+ * + *

#ThreadSafe#

+ * @since 1.0 + */ +//@Immutable +public class ObjectUtils { + + /** + *

Singleton used as a {@code null} placeholder where + * {@code null} has another meaning.

+ * + *

For example, in a {@code HashMap} the + * {@link java.util.HashMap#get(java.lang.Object)} method returns + * {@code null} if the {@code Map} contains {@code null} or if there + * is no matching key. The {@code Null} placeholder can be used to + * distinguish between these two cases.

+ * + *

Another example is {@code Hashtable}, where {@code null} + * cannot be stored.

+ * + *

This instance is Serializable.

+ */ + public static final Null NULL = new Null(); + + /** + *

{@code ObjectUtils} instances should NOT be constructed in + * standard programming. Instead, the static methods on the class should + * be used, such as {@code ObjectUtils.defaultIfNull("a","b");}.

+ * + *

This constructor is public to permit tools that require a JavaBean + * instance to operate.

+ */ + public ObjectUtils() { + super(); + } + + // Defaulting + //----------------------------------------------------------------------- + /** + *

Returns a default value if the object passed is {@code null}.

+ * + *
+     * ObjectUtils.defaultIfNull(null, null)      = null
+     * ObjectUtils.defaultIfNull(null, "")        = ""
+     * ObjectUtils.defaultIfNull(null, "zz")      = "zz"
+     * ObjectUtils.defaultIfNull("abc", *)        = "abc"
+     * ObjectUtils.defaultIfNull(Boolean.TRUE, *) = Boolean.TRUE
+     * 
+ * + * @param the type of the object + * @param object the {@code Object} to test, may be {@code null} + * @param defaultValue the default value to return, may be {@code null} + * @return {@code object} if it is not {@code null}, defaultValue otherwise + */ + public static T defaultIfNull(final T object, final T defaultValue) { + return object != null ? object : defaultValue; + } + + /** + *

Returns the first value in the array which is not {@code null}. + * If all the values are {@code null} or the array is {@code null} + * or empty then {@code null} is returned.

+ * + *
+     * ObjectUtils.firstNonNull(null, null)      = null
+     * ObjectUtils.firstNonNull(null, "")        = ""
+     * ObjectUtils.firstNonNull(null, null, "")  = ""
+     * ObjectUtils.firstNonNull(null, "zz")      = "zz"
+     * ObjectUtils.firstNonNull("abc", *)        = "abc"
+     * ObjectUtils.firstNonNull(null, "xyz", *)  = "xyz"
+     * ObjectUtils.firstNonNull(Boolean.TRUE, *) = Boolean.TRUE
+     * ObjectUtils.firstNonNull()                = null
+     * 
+ * + * @param the component type of the array + * @param values the values to test, may be {@code null} or empty + * @return the first value from {@code values} which is not {@code null}, + * or {@code null} if there are no non-null values + * @since 3.0 + */ + public static T firstNonNull(final T... values) { + if (values != null) { + for (final T val : values) { + if (val != null) { + return val; + } + } + } + return null; + } + + /** + * Checks if any value in the given array is not {@code null}. + * + *

+ * If all the values are {@code null} or the array is {@code null} + * or empty then {@code false} is returned. Otherwise {@code true} is returned. + *

+ * + *
+     * ObjectUtils.anyNotNull(*)                = true
+     * ObjectUtils.anyNotNull(*, null)          = true
+     * ObjectUtils.anyNotNull(null, *)          = true
+     * ObjectUtils.anyNotNull(null, null, *, *) = true
+     * ObjectUtils.anyNotNull(null)             = false
+     * ObjectUtils.anyNotNull(null, null)       = false
+     * 
+ * + * @param values the values to test, may be {@code null} or empty + * @return {@code true} if there is at least one non-null value in the array, + * {@code false} if all values in the array are {@code null}s. + * If the array is {@code null} or empty {@code false} is also returned. + * @since 3.5 + */ + public static boolean anyNotNull(final Object... values) { + return firstNonNull(values) != null; + } + + /** + * Checks if all values in the array are not {@code nulls}. + * + *

+ * If any value is {@code null} or the array is {@code null} then + * {@code false} is returned. If all elements in array are not + * {@code null} or the array is empty (contains no elements) {@code true} + * is returned. + *

+ * + *
+     * ObjectUtils.allNotNull(*)             = true
+     * ObjectUtils.allNotNull(*, *)          = true
+     * ObjectUtils.allNotNull(null)          = false
+     * ObjectUtils.allNotNull(null, null)    = false
+     * ObjectUtils.allNotNull(null, *)       = false
+     * ObjectUtils.allNotNull(*, null)       = false
+     * ObjectUtils.allNotNull(*, *, null, *) = false
+     * 
+ * + * @param values the values to test, may be {@code null} or empty + * @return {@code false} if there is at least one {@code null} value in the array or the array is {@code null}, + * {@code true} if all values in the array are not {@code null}s or array contains no elements. + * @since 3.5 + */ + public static boolean allNotNull(final Object... values) { + if (values == null) { + return false; + } + + for (final Object val : values) { + if (val == null) { + return false; + } + } + + return true; + } + + // Null-safe equals/hashCode + //----------------------------------------------------------------------- + /** + *

Compares two objects for equality, where either one or both + * objects may be {@code null}.

+ * + *
+     * ObjectUtils.equals(null, null)                  = true
+     * ObjectUtils.equals(null, "")                    = false
+     * ObjectUtils.equals("", null)                    = false
+     * ObjectUtils.equals("", "")                      = true
+     * ObjectUtils.equals(Boolean.TRUE, null)          = false
+     * ObjectUtils.equals(Boolean.TRUE, "true")        = false
+     * ObjectUtils.equals(Boolean.TRUE, Boolean.TRUE)  = true
+     * ObjectUtils.equals(Boolean.TRUE, Boolean.FALSE) = false
+     * 
+ * + * @param object1 the first object, may be {@code null} + * @param object2 the second object, may be {@code null} + * @return {@code true} if the values of both objects are the same + * @deprecated this method has been replaced by {@code java.util.Objects.equals(Object, Object)} in Java 7 and will + * be removed from future releases. + */ + @Deprecated + public static boolean equals(final Object object1, final Object object2) { + if (object1 == object2) { + return true; + } + if (object1 == null || object2 == null) { + return false; + } + return object1.equals(object2); + } + + /** + *

Compares two objects for inequality, where either one or both + * objects may be {@code null}.

+ * + *
+     * ObjectUtils.notEqual(null, null)                  = false
+     * ObjectUtils.notEqual(null, "")                    = true
+     * ObjectUtils.notEqual("", null)                    = true
+     * ObjectUtils.notEqual("", "")                      = false
+     * ObjectUtils.notEqual(Boolean.TRUE, null)          = true
+     * ObjectUtils.notEqual(Boolean.TRUE, "true")        = true
+     * ObjectUtils.notEqual(Boolean.TRUE, Boolean.TRUE)  = false
+     * ObjectUtils.notEqual(Boolean.TRUE, Boolean.FALSE) = true
+     * 
+ * + * @param object1 the first object, may be {@code null} + * @param object2 the second object, may be {@code null} + * @return {@code false} if the values of both objects are the same + */ + public static boolean notEqual(final Object object1, final Object object2) { + return ObjectUtils.equals(object1, object2) == false; + } + + /** + *

Gets the hash code of an object returning zero when the + * object is {@code null}.

+ * + *
+     * ObjectUtils.hashCode(null)   = 0
+     * ObjectUtils.hashCode(obj)    = obj.hashCode()
+     * 
+ * + * @param obj the object to obtain the hash code of, may be {@code null} + * @return the hash code of the object, or zero if null + * @since 2.1 + * @deprecated this method has been replaced by {@code java.util.Objects.hashCode(Object)} in Java 7 and will be + * removed in future releases + */ + @Deprecated + public static int hashCode(final Object obj) { + // hashCode(Object) retained for performance, as hash code is often critical + return obj == null ? 0 : obj.hashCode(); + } + + /** + *

Gets the hash code for multiple objects.

+ * + *

This allows a hash code to be rapidly calculated for a number of objects. + * The hash code for a single object is the not same as {@link #hashCode(Object)}. + * The hash code for multiple objects is the same as that calculated by an + * {@code ArrayList} containing the specified objects.

+ * + *
+     * ObjectUtils.hashCodeMulti()                 = 1
+     * ObjectUtils.hashCodeMulti((Object[]) null)  = 1
+     * ObjectUtils.hashCodeMulti(a)                = 31 + a.hashCode()
+     * ObjectUtils.hashCodeMulti(a,b)              = (31 + a.hashCode()) * 31 + b.hashCode()
+     * ObjectUtils.hashCodeMulti(a,b,c)            = ((31 + a.hashCode()) * 31 + b.hashCode()) * 31 + c.hashCode()
+     * 
+ * + * @param objects the objects to obtain the hash code of, may be {@code null} + * @return the hash code of the objects, or zero if null + * @since 3.0 + * @deprecated this method has been replaced by {@code java.util.Objects.hash(Object...)} in Java 7 and will be + * removed in future releases. + */ + @Deprecated + public static int hashCodeMulti(final Object... objects) { + int hash = 1; + if (objects != null) { + for (final Object object : objects) { + final int tmpHash = ObjectUtils.hashCode(object); + hash = hash * 31 + tmpHash; + } + } + return hash; + } + + // Identity ToString + //----------------------------------------------------------------------- + /** + *

Gets the toString that would be produced by {@code Object} + * if a class did not override toString itself. {@code null} + * will return {@code null}.

+ * + *
+     * ObjectUtils.identityToString(null)         = null
+     * ObjectUtils.identityToString("")           = "java.lang.String@1e23"
+     * ObjectUtils.identityToString(Boolean.TRUE) = "java.lang.Boolean@7fa"
+     * 
+ * + * @param object the object to create a toString for, may be + * {@code null} + * @return the default toString text, or {@code null} if + * {@code null} passed in + */ + public static String identityToString(final Object object) { + if (object == null) { + return null; + } + final StringBuilder builder = new StringBuilder(); + identityToString(builder, object); + return builder.toString(); + } + + /** + *

Appends the toString that would be produced by {@code Object} + * if a class did not override toString itself. {@code null} + * will throw a NullPointerException for either of the two parameters.

+ * + *
+     * ObjectUtils.identityToString(appendable, "")            = appendable.append("java.lang.String@1e23"
+     * ObjectUtils.identityToString(appendable, Boolean.TRUE)  = appendable.append("java.lang.Boolean@7fa"
+     * ObjectUtils.identityToString(appendable, Boolean.TRUE)  = appendable.append("java.lang.Boolean@7fa")
+     * 
+ * + * @param appendable the appendable to append to + * @param object the object to create a toString for + * @throws IOException if an I/O error occurs + * @since 3.2 + */ + public static void identityToString(final Appendable appendable, final Object object) throws IOException { + if (object == null) { + throw new NullPointerException("Cannot get the toString of a null identity"); + } + appendable.append(object.getClass().getName()) + .append('@') + .append(Integer.toHexString(System.identityHashCode(object))); + } + + /** + *

Appends the toString that would be produced by {@code Object} + * if a class did not override toString itself. {@code null} + * will throw a NullPointerException for either of the two parameters.

+ * + *
+     * ObjectUtils.identityToString(builder, "")            = builder.append("java.lang.String@1e23"
+     * ObjectUtils.identityToString(builder, Boolean.TRUE)  = builder.append("java.lang.Boolean@7fa"
+     * ObjectUtils.identityToString(builder, Boolean.TRUE)  = builder.append("java.lang.Boolean@7fa")
+     * 
+ * + * @param builder the builder to append to + * @param object the object to create a toString for + * @since 3.2 + */ + public static void identityToString(final StrBuilder builder, final Object object) { + if (object == null) { + throw new NullPointerException("Cannot get the toString of a null identity"); + } + builder.append(object.getClass().getName()) + .append('@') + .append(Integer.toHexString(System.identityHashCode(object))); + } + + /** + *

Appends the toString that would be produced by {@code Object} + * if a class did not override toString itself. {@code null} + * will throw a NullPointerException for either of the two parameters.

+ * + *
+     * ObjectUtils.identityToString(buf, "")            = buf.append("java.lang.String@1e23"
+     * ObjectUtils.identityToString(buf, Boolean.TRUE)  = buf.append("java.lang.Boolean@7fa"
+     * ObjectUtils.identityToString(buf, Boolean.TRUE)  = buf.append("java.lang.Boolean@7fa")
+     * 
+ * + * @param buffer the buffer to append to + * @param object the object to create a toString for + * @since 2.4 + */ + public static void identityToString(final StringBuffer buffer, final Object object) { + if (object == null) { + throw new NullPointerException("Cannot get the toString of a null identity"); + } + buffer.append(object.getClass().getName()) + .append('@') + .append(Integer.toHexString(System.identityHashCode(object))); + } + + /** + *

Appends the toString that would be produced by {@code Object} + * if a class did not override toString itself. {@code null} + * will throw a NullPointerException for either of the two parameters.

+ * + *
+     * ObjectUtils.identityToString(builder, "")            = builder.append("java.lang.String@1e23"
+     * ObjectUtils.identityToString(builder, Boolean.TRUE)  = builder.append("java.lang.Boolean@7fa"
+     * ObjectUtils.identityToString(builder, Boolean.TRUE)  = builder.append("java.lang.Boolean@7fa")
+     * 
+ * + * @param builder the builder to append to + * @param object the object to create a toString for + * @since 3.2 + */ + public static void identityToString(final StringBuilder builder, final Object object) { + if (object == null) { + throw new NullPointerException("Cannot get the toString of a null identity"); + } + builder.append(object.getClass().getName()) + .append('@') + .append(Integer.toHexString(System.identityHashCode(object))); + } + + // ToString + //----------------------------------------------------------------------- + /** + *

Gets the {@code toString} of an {@code Object} returning + * an empty string ("") if {@code null} input.

+ * + *
+     * ObjectUtils.toString(null)         = ""
+     * ObjectUtils.toString("")           = ""
+     * ObjectUtils.toString("bat")        = "bat"
+     * ObjectUtils.toString(Boolean.TRUE) = "true"
+     * 
+ * + * @see StringUtils#defaultString(String) + * @see String#valueOf(Object) + * @param obj the Object to {@code toString}, may be null + * @return the passed in Object's toString, or {@code ""} if {@code null} input + * @since 2.0 + * @deprecated this method has been replaced by {@code java.util.Objects.toString(Object)} in Java 7 and will be + * removed in future releases. Note however that said method will return "null" for null references, while this + * method returns and empty String. To preserve behavior use {@code java.util.Objects.toString(myObject, "")} + */ + @Deprecated + public static String toString(final Object obj) { + return obj == null ? StringUtils.EMPTY : obj.toString(); + } + + /** + *

Gets the {@code toString} of an {@code Object} returning + * a specified text if {@code null} input.

+ * + *
+     * ObjectUtils.toString(null, null)           = null
+     * ObjectUtils.toString(null, "null")         = "null"
+     * ObjectUtils.toString("", "null")           = ""
+     * ObjectUtils.toString("bat", "null")        = "bat"
+     * ObjectUtils.toString(Boolean.TRUE, "null") = "true"
+     * 
+ * + * @see StringUtils#defaultString(String,String) + * @see String#valueOf(Object) + * @param obj the Object to {@code toString}, may be null + * @param nullStr the String to return if {@code null} input, may be null + * @return the passed in Object's toString, or {@code nullStr} if {@code null} input + * @since 2.0 + * @deprecated this method has been replaced by {@code java.util.Objects.toString(Object, String)} in Java 7 and + * will be removed in future releases. + */ + @Deprecated + public static String toString(final Object obj, final String nullStr) { + return obj == null ? nullStr : obj.toString(); + } + + // Comparable + //----------------------------------------------------------------------- + /** + *

Null safe comparison of Comparables.

+ * + * @param type of the values processed by this method + * @param values the set of comparable values, may be null + * @return + *
    + *
  • If any objects are non-null and unequal, the lesser object. + *
  • If all objects are non-null and equal, the first. + *
  • If any of the comparables are null, the lesser of the non-null objects. + *
  • If all the comparables are null, null is returned. + *
+ */ +// Comparable +// ----------------------------------------------------------------------- +/** + *

Null safe comparison of Comparables.

+ * + * @param + * type of the values processed by this method + * @param values + * the set of comparable values, may be null + * @return
    +
  • If any objects are non-null and unequal, the lesser object. +
  • If all objects are non-null and equal, the first. +
  • If any of the comparables are null, the lesser of the non-null objects. +
  • If all the comparables are null, null is returned. +
+ */ +public static > T min(final T... values) { + T result = null; + { + for (final T value : /* NPEX_NULL_EXP */ + values) { + if (org.apache.commons.lang3.ObjectUtils.compare(value, result, true) < 0) { + result = value; + } + } + } + return result; +} + + /** + *

Null safe comparison of Comparables.

+ * + * @param type of the values processed by this method + * @param values the set of comparable values, may be null + * @return + *
    + *
  • If any objects are non-null and unequal, the greater object. + *
  • If all objects are non-null and equal, the first. + *
  • If any of the comparables are null, the greater of the non-null objects. + *
  • If all the comparables are null, null is returned. + *
+ */ + public static > T max(final T... values) { + T result = null; + if (values != null) { + for (final T value : values) { + if (compare(value, result, false) > 0) { + result = value; + } + } + } + return result; + } + + /** + *

Null safe comparison of Comparables. + * {@code null} is assumed to be less than a non-{@code null} value.

+ * + * @param type of the values processed by this method + * @param c1 the first comparable, may be null + * @param c2 the second comparable, may be null + * @return a negative value if c1 < c2, zero if c1 = c2 + * and a positive value if c1 > c2 + */ + public static > int compare(final T c1, final T c2) { + return compare(c1, c2, false); + } + + /** + *

Null safe comparison of Comparables.

+ * + * @param type of the values processed by this method + * @param c1 the first comparable, may be null + * @param c2 the second comparable, may be null + * @param nullGreater if true {@code null} is considered greater + * than a non-{@code null} value or if false {@code null} is + * considered less than a Non-{@code null} value + * @return a negative value if c1 < c2, zero if c1 = c2 + * and a positive value if c1 > c2 + * @see java.util.Comparator#compare(Object, Object) + */ + public static > int compare(final T c1, final T c2, final boolean nullGreater) { + if (c1 == c2) { + return 0; + } else if (c1 == null) { + return nullGreater ? 1 : -1; + } else if (c2 == null) { + return nullGreater ? -1 : 1; + } + return c1.compareTo(c2); + } + + /** + * Find the "best guess" middle value among comparables. If there is an even + * number of total values, the lower of the two middle values will be returned. + * @param type of values processed by this method + * @param items to compare + * @return T at middle position + * @throws NullPointerException if items is {@code null} + * @throws IllegalArgumentException if items is empty or contains {@code null} values + * @since 3.0.1 + */ + public static > T median(final T... items) { + Validate.notEmpty(items); + Validate.noNullElements(items); + final TreeSet sort = new TreeSet(); + Collections.addAll(sort, items); + @SuppressWarnings("unchecked") //we know all items added were T instances + final + T result = (T) sort.toArray()[(sort.size() - 1) / 2]; + return result; + } + + /** + * Find the "best guess" middle value among comparables. If there is an even + * number of total values, the lower of the two middle values will be returned. + * @param type of values processed by this method + * @param comparator to use for comparisons + * @param items to compare + * @return T at middle position + * @throws NullPointerException if items or comparator is {@code null} + * @throws IllegalArgumentException if items is empty or contains {@code null} values + * @since 3.0.1 + */ + public static T median(final Comparator comparator, final T... items) { + Validate.notEmpty(items, "null/empty items"); + Validate.noNullElements(items); + Validate.notNull(comparator, "null comparator"); + final TreeSet sort = new TreeSet(comparator); + Collections.addAll(sort, items); + @SuppressWarnings("unchecked") //we know all items added were T instances + final + T result = (T) sort.toArray()[(sort.size() - 1) / 2]; + return result; + } + + // Mode + //----------------------------------------------------------------------- + /** + * Find the most frequently occurring item. + * + * @param type of values processed by this method + * @param items to check + * @return most populous T, {@code null} if non-unique or no items supplied + * @since 3.0.1 + */ + public static T mode(final T... items) { + if (ArrayUtils.isNotEmpty(items)) { + final HashMap occurrences = new HashMap(items.length); + for (final T t : items) { + final MutableInt count = occurrences.get(t); + if (count == null) { + occurrences.put(t, new MutableInt(1)); + } else { + count.increment(); + } + } + T result = null; + int max = 0; + for (final Map.Entry e : occurrences.entrySet()) { + final int cmp = e.getValue().intValue(); + if (cmp == max) { + result = null; + } else if (cmp > max) { + max = cmp; + result = e.getKey(); + } + } + return result; + } + return null; + } + + // cloning + //----------------------------------------------------------------------- + /** + *

Clone an object.

+ * + * @param the type of the object + * @param obj the object to clone, null returns null + * @return the clone if the object implements {@link Cloneable} otherwise {@code null} + * @throws CloneFailedException if the object is cloneable and the clone operation fails + * @since 3.0 + */ + public static T clone(final T obj) { + if (obj instanceof Cloneable) { + final Object result; + if (obj.getClass().isArray()) { + final Class componentType = obj.getClass().getComponentType(); + if (!componentType.isPrimitive()) { + result = ((Object[]) obj).clone(); + } else { + int length = Array.getLength(obj); + result = Array.newInstance(componentType, length); + while (length-- > 0) { + Array.set(result, length, Array.get(obj, length)); + } + } + } else { + try { + final Method clone = obj.getClass().getMethod("clone"); + result = clone.invoke(obj); + } catch (final NoSuchMethodException e) { + throw new CloneFailedException("Cloneable type " + + obj.getClass().getName() + + " has no clone method", e); + } catch (final IllegalAccessException e) { + throw new CloneFailedException("Cannot clone Cloneable type " + + obj.getClass().getName(), e); + } catch (final InvocationTargetException e) { + throw new CloneFailedException("Exception cloning Cloneable type " + + obj.getClass().getName(), e.getCause()); + } + } + @SuppressWarnings("unchecked") // OK because input is of type T + final T checked = (T) result; + return checked; + } + + return null; + } + + /** + *

Clone an object if possible.

+ * + *

This method is similar to {@link #clone(Object)}, but will return the provided + * instance as the return value instead of {@code null} if the instance + * is not cloneable. This is more convenient if the caller uses different + * implementations (e.g. of a service) and some of the implementations do not allow concurrent + * processing or have state. In such cases the implementation can simply provide a proper + * clone implementation and the caller's code does not have to change.

+ * + * @param the type of the object + * @param obj the object to clone, null returns null + * @return the clone if the object implements {@link Cloneable} otherwise the object itself + * @throws CloneFailedException if the object is cloneable and the clone operation fails + * @since 3.0 + */ + public static T cloneIfPossible(final T obj) { + final T clone = clone(obj); + return clone == null ? obj : clone; + } + + // Null + //----------------------------------------------------------------------- + /** + *

Class used as a null placeholder where {@code null} + * has another meaning.

+ * + *

For example, in a {@code HashMap} the + * {@link java.util.HashMap#get(java.lang.Object)} method returns + * {@code null} if the {@code Map} contains {@code null} or if there is + * no matching key. The {@code Null} placeholder can be used to distinguish + * between these two cases.

+ * + *

Another example is {@code Hashtable}, where {@code null} + * cannot be stored.

+ */ + public static class Null implements Serializable { + /** + * Required for serialization support. Declare serialization compatibility with Commons Lang 1.0 + * + * @see java.io.Serializable + */ + private static final long serialVersionUID = 7092611880189329093L; + + /** + * Restricted constructor - singleton. + */ + Null() { + super(); + } + + /** + *

Ensure singleton.

+ * + * @return the singleton value + */ + private Object readResolve() { + return ObjectUtils.NULL; + } + } + + + // Constants (LANG-816): + /* + These methods ensure constants are not inlined by javac. + For example, typically a developer might declare a constant like so: + + public final static int MAGIC_NUMBER = 5; + + Should a different jar file refer to this, and the MAGIC_NUMBER + is changed a later date (e.g., MAGIC_NUMBER = 6), the different jar + file will need to recompile itself. This is because javac + typically inlines the primitive or String constant directly into + the bytecode, and removes the reference to the MAGIC_NUMBER field. + + To help the other jar (so that it does not need to recompile + when constants are changed) the original developer can declare + their constant using one of the CONST() utility methods, instead: + + public final static int MAGIC_NUMBER = CONST(5); + */ + + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static boolean MAGIC_FLAG = ObjectUtils.CONST(true);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the boolean value to return + * @return the boolean v, unchanged + * @since 3.2 + */ + public static boolean CONST(final boolean v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static byte MAGIC_BYTE = ObjectUtils.CONST((byte) 127);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the byte value to return + * @return the byte v, unchanged + * @since 3.2 + */ + public static byte CONST(final byte v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static byte MAGIC_BYTE = ObjectUtils.CONST_BYTE(127);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the byte literal (as an int) value to return + * @throws IllegalArgumentException if the value passed to v + * is larger than a byte, that is, smaller than -128 or + * larger than 127. + * @return the byte v, unchanged + * @since 3.2 + */ + public static byte CONST_BYTE(final int v) throws IllegalArgumentException { + if (v < Byte.MIN_VALUE || v > Byte.MAX_VALUE) { + throw new IllegalArgumentException("Supplied value must be a valid byte literal between -128 and 127: [" + v + "]"); + } + return (byte) v; + } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static char MAGIC_CHAR = ObjectUtils.CONST('a');
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the char value to return + * @return the char v, unchanged + * @since 3.2 + */ + public static char CONST(final char v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static short MAGIC_SHORT = ObjectUtils.CONST((short) 123);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the short value to return + * @return the short v, unchanged + * @since 3.2 + */ + public static short CONST(final short v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static short MAGIC_SHORT = ObjectUtils.CONST_SHORT(127);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the short literal (as an int) value to return + * @throws IllegalArgumentException if the value passed to v + * is larger than a short, that is, smaller than -32768 or + * larger than 32767. + * @return the byte v, unchanged + * @since 3.2 + */ + public static short CONST_SHORT(final int v) throws IllegalArgumentException { + if (v < Short.MIN_VALUE || v > Short.MAX_VALUE) { + throw new IllegalArgumentException("Supplied value must be a valid byte literal between -32768 and 32767: [" + v + "]"); + } + return (short) v; + } + + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static int MAGIC_INT = ObjectUtils.CONST(123);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the int value to return + * @return the int v, unchanged + * @since 3.2 + */ + public static int CONST(final int v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static long MAGIC_LONG = ObjectUtils.CONST(123L);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the long value to return + * @return the long v, unchanged + * @since 3.2 + */ + public static long CONST(final long v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static float MAGIC_FLOAT = ObjectUtils.CONST(1.0f);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the float value to return + * @return the float v, unchanged + * @since 3.2 + */ + public static float CONST(final float v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static double MAGIC_DOUBLE = ObjectUtils.CONST(1.0);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the double value to return + * @return the double v, unchanged + * @since 3.2 + */ + public static double CONST(final double v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static String MAGIC_STRING = ObjectUtils.CONST("abc");
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param the Object type + * @param v the genericized Object value to return (typically a String). + * @return the genericized Object v, unchanged (typically a String). + * @since 3.2 + */ + public static T CONST(final T v) { return v; } + +} diff --git a/Java/commons-lang-ObjectUtils_503/metadata.json b/Java/commons-lang-ObjectUtils_503/metadata.json new file mode 100644 index 000000000..9a7927a95 --- /dev/null +++ b/Java/commons-lang-ObjectUtils_503/metadata.json @@ -0,0 +1,21 @@ +{ + "language": "java", + "id": "commons-lang-ObjectUtils_503", + "buggyPath": ".", + "referencePath": null, + "buildCommand": "mvn package -V -B -Denforcer.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true -Drat.skip=true -Dlicense.skip=true -Dfindbugs.skip=true -Dgpg.skip=true -Dskip.npm=true -Dskip.gulp=true -Dskip.bower=true -Drat.numUnapprovedLicenses=100 -DskipTests=true -DskipITs=true -Dtest=None -DfailIfNoTests=false", + "testCommand": "mvn test -V -B -Denforcer.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true -Drat.skip=true -Dlicense.skip=true -Dfindbugs.skip=true -Dgpg.skip=true -Dskip.npm=true -Dskip.gulp=true -Dskip.bower=true -Drat.numUnapprovedLicenses=100", + "categories": [ + "safety", + "npe" + ], + "npe": { + "filepath": "src/main/java/org/apache/commons/lang3/ObjectUtils.java", + "line": 521, + "npe_method": "min", + "deref_field": "values", + "npe_class": "ObjectUtils", + "repo": "commons-lang", + "bug_id": "ObjectUtils_503" + } +} diff --git a/Java/commons-lang-ObjectUtils_503/npe.json b/Java/commons-lang-ObjectUtils_503/npe.json new file mode 100644 index 000000000..774ca40cc --- /dev/null +++ b/Java/commons-lang-ObjectUtils_503/npe.json @@ -0,0 +1,7 @@ +{ + "filepath": "src/main/java/org/apache/commons/lang3/ObjectUtils.java", + "line": 521, + "npe_method": "min", + "deref_field": "values", + "npe_class": "ObjectUtils" +} \ No newline at end of file diff --git a/Java/commons-lang-ObjectUtils_528/Dockerfile b/Java/commons-lang-ObjectUtils_528/Dockerfile new file mode 100644 index 000000000..7b7fbe349 --- /dev/null +++ b/Java/commons-lang-ObjectUtils_528/Dockerfile @@ -0,0 +1,18 @@ +FROM ghcr.io/kupl/starlab-benchmarks/java-base:commons-lang + +ENV TZ=Asia/Seoul + +COPY ./metadata.json . +COPY ./npe.json . +COPY ./buggy.java /tmp/buggy.java +RUN export BUGGY_PATH=$(cat metadata.json | jq -r ".npe.filepath") \ + && export BUGGY_LINE=$(cat metadata.json | jq -r ".npe.line") \ + && export BUGGY_MTHD=$(cat metadata.json | jq -r ".npe.npe_method") \ + && mv /tmp/buggy.java $BUGGY_PATH \ + && echo "[{\"filepath\": \"$BUGGY_PATH\", \"line\": $BUGGY_LINE, \"method_name\": \"$BUGGY_MTHD\"}]" | jq . > traces.json + +RUN git init . && git add -A + +RUN $(cat metadata.json | jq -r ".buildCommand") + +RUN $(cat metadata.json | jq -r ".testCommand"); if [ $? -eq 0 ]; then exit 1; fi diff --git a/Java/commons-lang-ObjectUtils_528/buggy.java b/Java/commons-lang-ObjectUtils_528/buggy.java new file mode 100644 index 000000000..879602648 --- /dev/null +++ b/Java/commons-lang-ObjectUtils_528/buggy.java @@ -0,0 +1,1031 @@ +/* + * 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.Serializable; +import java.lang.reflect.Array; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.Map; +import java.util.TreeSet; + +import org.apache.commons.lang3.exception.CloneFailedException; +import org.apache.commons.lang3.mutable.MutableInt; +import org.apache.commons.lang3.text.StrBuilder; + +/** + *

Operations on {@code Object}.

+ * + *

This class tries to handle {@code null} input gracefully. + * An exception will generally not be thrown for a {@code null} input. + * Each method documents its behaviour in more detail.

+ * + *

#ThreadSafe#

+ * @since 1.0 + */ +//@Immutable +public class ObjectUtils { + + /** + *

Singleton used as a {@code null} placeholder where + * {@code null} has another meaning.

+ * + *

For example, in a {@code HashMap} the + * {@link java.util.HashMap#get(java.lang.Object)} method returns + * {@code null} if the {@code Map} contains {@code null} or if there + * is no matching key. The {@code Null} placeholder can be used to + * distinguish between these two cases.

+ * + *

Another example is {@code Hashtable}, where {@code null} + * cannot be stored.

+ * + *

This instance is Serializable.

+ */ + public static final Null NULL = new Null(); + + /** + *

{@code ObjectUtils} instances should NOT be constructed in + * standard programming. Instead, the static methods on the class should + * be used, such as {@code ObjectUtils.defaultIfNull("a","b");}.

+ * + *

This constructor is public to permit tools that require a JavaBean + * instance to operate.

+ */ + public ObjectUtils() { + super(); + } + + // Defaulting + //----------------------------------------------------------------------- + /** + *

Returns a default value if the object passed is {@code null}.

+ * + *
+     * ObjectUtils.defaultIfNull(null, null)      = null
+     * ObjectUtils.defaultIfNull(null, "")        = ""
+     * ObjectUtils.defaultIfNull(null, "zz")      = "zz"
+     * ObjectUtils.defaultIfNull("abc", *)        = "abc"
+     * ObjectUtils.defaultIfNull(Boolean.TRUE, *) = Boolean.TRUE
+     * 
+ * + * @param the type of the object + * @param object the {@code Object} to test, may be {@code null} + * @param defaultValue the default value to return, may be {@code null} + * @return {@code object} if it is not {@code null}, defaultValue otherwise + */ + public static T defaultIfNull(final T object, final T defaultValue) { + return object != null ? object : defaultValue; + } + + /** + *

Returns the first value in the array which is not {@code null}. + * If all the values are {@code null} or the array is {@code null} + * or empty then {@code null} is returned.

+ * + *
+     * ObjectUtils.firstNonNull(null, null)      = null
+     * ObjectUtils.firstNonNull(null, "")        = ""
+     * ObjectUtils.firstNonNull(null, null, "")  = ""
+     * ObjectUtils.firstNonNull(null, "zz")      = "zz"
+     * ObjectUtils.firstNonNull("abc", *)        = "abc"
+     * ObjectUtils.firstNonNull(null, "xyz", *)  = "xyz"
+     * ObjectUtils.firstNonNull(Boolean.TRUE, *) = Boolean.TRUE
+     * ObjectUtils.firstNonNull()                = null
+     * 
+ * + * @param the component type of the array + * @param values the values to test, may be {@code null} or empty + * @return the first value from {@code values} which is not {@code null}, + * or {@code null} if there are no non-null values + * @since 3.0 + */ + public static T firstNonNull(final T... values) { + if (values != null) { + for (final T val : values) { + if (val != null) { + return val; + } + } + } + return null; + } + + /** + * Checks if any value in the given array is not {@code null}. + * + *

+ * If all the values are {@code null} or the array is {@code null} + * or empty then {@code false} is returned. Otherwise {@code true} is returned. + *

+ * + *
+     * ObjectUtils.anyNotNull(*)                = true
+     * ObjectUtils.anyNotNull(*, null)          = true
+     * ObjectUtils.anyNotNull(null, *)          = true
+     * ObjectUtils.anyNotNull(null, null, *, *) = true
+     * ObjectUtils.anyNotNull(null)             = false
+     * ObjectUtils.anyNotNull(null, null)       = false
+     * 
+ * + * @param values the values to test, may be {@code null} or empty + * @return {@code true} if there is at least one non-null value in the array, + * {@code false} if all values in the array are {@code null}s. + * If the array is {@code null} or empty {@code false} is also returned. + * @since 3.5 + */ + public static boolean anyNotNull(final Object... values) { + return firstNonNull(values) != null; + } + + /** + * Checks if all values in the array are not {@code nulls}. + * + *

+ * If any value is {@code null} or the array is {@code null} then + * {@code false} is returned. If all elements in array are not + * {@code null} or the array is empty (contains no elements) {@code true} + * is returned. + *

+ * + *
+     * ObjectUtils.allNotNull(*)             = true
+     * ObjectUtils.allNotNull(*, *)          = true
+     * ObjectUtils.allNotNull(null)          = false
+     * ObjectUtils.allNotNull(null, null)    = false
+     * ObjectUtils.allNotNull(null, *)       = false
+     * ObjectUtils.allNotNull(*, null)       = false
+     * ObjectUtils.allNotNull(*, *, null, *) = false
+     * 
+ * + * @param values the values to test, may be {@code null} or empty + * @return {@code false} if there is at least one {@code null} value in the array or the array is {@code null}, + * {@code true} if all values in the array are not {@code null}s or array contains no elements. + * @since 3.5 + */ + public static boolean allNotNull(final Object... values) { + if (values == null) { + return false; + } + + for (final Object val : values) { + if (val == null) { + return false; + } + } + + return true; + } + + // Null-safe equals/hashCode + //----------------------------------------------------------------------- + /** + *

Compares two objects for equality, where either one or both + * objects may be {@code null}.

+ * + *
+     * ObjectUtils.equals(null, null)                  = true
+     * ObjectUtils.equals(null, "")                    = false
+     * ObjectUtils.equals("", null)                    = false
+     * ObjectUtils.equals("", "")                      = true
+     * ObjectUtils.equals(Boolean.TRUE, null)          = false
+     * ObjectUtils.equals(Boolean.TRUE, "true")        = false
+     * ObjectUtils.equals(Boolean.TRUE, Boolean.TRUE)  = true
+     * ObjectUtils.equals(Boolean.TRUE, Boolean.FALSE) = false
+     * 
+ * + * @param object1 the first object, may be {@code null} + * @param object2 the second object, may be {@code null} + * @return {@code true} if the values of both objects are the same + * @deprecated this method has been replaced by {@code java.util.Objects.equals(Object, Object)} in Java 7 and will + * be removed from future releases. + */ + @Deprecated + public static boolean equals(final Object object1, final Object object2) { + if (object1 == object2) { + return true; + } + if (object1 == null || object2 == null) { + return false; + } + return object1.equals(object2); + } + + /** + *

Compares two objects for inequality, where either one or both + * objects may be {@code null}.

+ * + *
+     * ObjectUtils.notEqual(null, null)                  = false
+     * ObjectUtils.notEqual(null, "")                    = true
+     * ObjectUtils.notEqual("", null)                    = true
+     * ObjectUtils.notEqual("", "")                      = false
+     * ObjectUtils.notEqual(Boolean.TRUE, null)          = true
+     * ObjectUtils.notEqual(Boolean.TRUE, "true")        = true
+     * ObjectUtils.notEqual(Boolean.TRUE, Boolean.TRUE)  = false
+     * ObjectUtils.notEqual(Boolean.TRUE, Boolean.FALSE) = true
+     * 
+ * + * @param object1 the first object, may be {@code null} + * @param object2 the second object, may be {@code null} + * @return {@code false} if the values of both objects are the same + */ + public static boolean notEqual(final Object object1, final Object object2) { + return ObjectUtils.equals(object1, object2) == false; + } + + /** + *

Gets the hash code of an object returning zero when the + * object is {@code null}.

+ * + *
+     * ObjectUtils.hashCode(null)   = 0
+     * ObjectUtils.hashCode(obj)    = obj.hashCode()
+     * 
+ * + * @param obj the object to obtain the hash code of, may be {@code null} + * @return the hash code of the object, or zero if null + * @since 2.1 + * @deprecated this method has been replaced by {@code java.util.Objects.hashCode(Object)} in Java 7 and will be + * removed in future releases + */ + @Deprecated + public static int hashCode(final Object obj) { + // hashCode(Object) retained for performance, as hash code is often critical + return obj == null ? 0 : obj.hashCode(); + } + + /** + *

Gets the hash code for multiple objects.

+ * + *

This allows a hash code to be rapidly calculated for a number of objects. + * The hash code for a single object is the not same as {@link #hashCode(Object)}. + * The hash code for multiple objects is the same as that calculated by an + * {@code ArrayList} containing the specified objects.

+ * + *
+     * ObjectUtils.hashCodeMulti()                 = 1
+     * ObjectUtils.hashCodeMulti((Object[]) null)  = 1
+     * ObjectUtils.hashCodeMulti(a)                = 31 + a.hashCode()
+     * ObjectUtils.hashCodeMulti(a,b)              = (31 + a.hashCode()) * 31 + b.hashCode()
+     * ObjectUtils.hashCodeMulti(a,b,c)            = ((31 + a.hashCode()) * 31 + b.hashCode()) * 31 + c.hashCode()
+     * 
+ * + * @param objects the objects to obtain the hash code of, may be {@code null} + * @return the hash code of the objects, or zero if null + * @since 3.0 + * @deprecated this method has been replaced by {@code java.util.Objects.hash(Object...)} in Java 7 and will be + * removed in future releases. + */ + @Deprecated + public static int hashCodeMulti(final Object... objects) { + int hash = 1; + if (objects != null) { + for (final Object object : objects) { + final int tmpHash = ObjectUtils.hashCode(object); + hash = hash * 31 + tmpHash; + } + } + return hash; + } + + // Identity ToString + //----------------------------------------------------------------------- + /** + *

Gets the toString that would be produced by {@code Object} + * if a class did not override toString itself. {@code null} + * will return {@code null}.

+ * + *
+     * ObjectUtils.identityToString(null)         = null
+     * ObjectUtils.identityToString("")           = "java.lang.String@1e23"
+     * ObjectUtils.identityToString(Boolean.TRUE) = "java.lang.Boolean@7fa"
+     * 
+ * + * @param object the object to create a toString for, may be + * {@code null} + * @return the default toString text, or {@code null} if + * {@code null} passed in + */ + public static String identityToString(final Object object) { + if (object == null) { + return null; + } + final StringBuilder builder = new StringBuilder(); + identityToString(builder, object); + return builder.toString(); + } + + /** + *

Appends the toString that would be produced by {@code Object} + * if a class did not override toString itself. {@code null} + * will throw a NullPointerException for either of the two parameters.

+ * + *
+     * ObjectUtils.identityToString(appendable, "")            = appendable.append("java.lang.String@1e23"
+     * ObjectUtils.identityToString(appendable, Boolean.TRUE)  = appendable.append("java.lang.Boolean@7fa"
+     * ObjectUtils.identityToString(appendable, Boolean.TRUE)  = appendable.append("java.lang.Boolean@7fa")
+     * 
+ * + * @param appendable the appendable to append to + * @param object the object to create a toString for + * @throws IOException if an I/O error occurs + * @since 3.2 + */ + public static void identityToString(final Appendable appendable, final Object object) throws IOException { + if (object == null) { + throw new NullPointerException("Cannot get the toString of a null identity"); + } + appendable.append(object.getClass().getName()) + .append('@') + .append(Integer.toHexString(System.identityHashCode(object))); + } + + /** + *

Appends the toString that would be produced by {@code Object} + * if a class did not override toString itself. {@code null} + * will throw a NullPointerException for either of the two parameters.

+ * + *
+     * ObjectUtils.identityToString(builder, "")            = builder.append("java.lang.String@1e23"
+     * ObjectUtils.identityToString(builder, Boolean.TRUE)  = builder.append("java.lang.Boolean@7fa"
+     * ObjectUtils.identityToString(builder, Boolean.TRUE)  = builder.append("java.lang.Boolean@7fa")
+     * 
+ * + * @param builder the builder to append to + * @param object the object to create a toString for + * @since 3.2 + */ + public static void identityToString(final StrBuilder builder, final Object object) { + if (object == null) { + throw new NullPointerException("Cannot get the toString of a null identity"); + } + builder.append(object.getClass().getName()) + .append('@') + .append(Integer.toHexString(System.identityHashCode(object))); + } + + /** + *

Appends the toString that would be produced by {@code Object} + * if a class did not override toString itself. {@code null} + * will throw a NullPointerException for either of the two parameters.

+ * + *
+     * ObjectUtils.identityToString(buf, "")            = buf.append("java.lang.String@1e23"
+     * ObjectUtils.identityToString(buf, Boolean.TRUE)  = buf.append("java.lang.Boolean@7fa"
+     * ObjectUtils.identityToString(buf, Boolean.TRUE)  = buf.append("java.lang.Boolean@7fa")
+     * 
+ * + * @param buffer the buffer to append to + * @param object the object to create a toString for + * @since 2.4 + */ + public static void identityToString(final StringBuffer buffer, final Object object) { + if (object == null) { + throw new NullPointerException("Cannot get the toString of a null identity"); + } + buffer.append(object.getClass().getName()) + .append('@') + .append(Integer.toHexString(System.identityHashCode(object))); + } + + /** + *

Appends the toString that would be produced by {@code Object} + * if a class did not override toString itself. {@code null} + * will throw a NullPointerException for either of the two parameters.

+ * + *
+     * ObjectUtils.identityToString(builder, "")            = builder.append("java.lang.String@1e23"
+     * ObjectUtils.identityToString(builder, Boolean.TRUE)  = builder.append("java.lang.Boolean@7fa"
+     * ObjectUtils.identityToString(builder, Boolean.TRUE)  = builder.append("java.lang.Boolean@7fa")
+     * 
+ * + * @param builder the builder to append to + * @param object the object to create a toString for + * @since 3.2 + */ + public static void identityToString(final StringBuilder builder, final Object object) { + if (object == null) { + throw new NullPointerException("Cannot get the toString of a null identity"); + } + builder.append(object.getClass().getName()) + .append('@') + .append(Integer.toHexString(System.identityHashCode(object))); + } + + // ToString + //----------------------------------------------------------------------- + /** + *

Gets the {@code toString} of an {@code Object} returning + * an empty string ("") if {@code null} input.

+ * + *
+     * ObjectUtils.toString(null)         = ""
+     * ObjectUtils.toString("")           = ""
+     * ObjectUtils.toString("bat")        = "bat"
+     * ObjectUtils.toString(Boolean.TRUE) = "true"
+     * 
+ * + * @see StringUtils#defaultString(String) + * @see String#valueOf(Object) + * @param obj the Object to {@code toString}, may be null + * @return the passed in Object's toString, or {@code ""} if {@code null} input + * @since 2.0 + * @deprecated this method has been replaced by {@code java.util.Objects.toString(Object)} in Java 7 and will be + * removed in future releases. Note however that said method will return "null" for null references, while this + * method returns and empty String. To preserve behavior use {@code java.util.Objects.toString(myObject, "")} + */ + @Deprecated + public static String toString(final Object obj) { + return obj == null ? StringUtils.EMPTY : obj.toString(); + } + + /** + *

Gets the {@code toString} of an {@code Object} returning + * a specified text if {@code null} input.

+ * + *
+     * ObjectUtils.toString(null, null)           = null
+     * ObjectUtils.toString(null, "null")         = "null"
+     * ObjectUtils.toString("", "null")           = ""
+     * ObjectUtils.toString("bat", "null")        = "bat"
+     * ObjectUtils.toString(Boolean.TRUE, "null") = "true"
+     * 
+ * + * @see StringUtils#defaultString(String,String) + * @see String#valueOf(Object) + * @param obj the Object to {@code toString}, may be null + * @param nullStr the String to return if {@code null} input, may be null + * @return the passed in Object's toString, or {@code nullStr} if {@code null} input + * @since 2.0 + * @deprecated this method has been replaced by {@code java.util.Objects.toString(Object, String)} in Java 7 and + * will be removed in future releases. + */ + @Deprecated + public static String toString(final Object obj, final String nullStr) { + return obj == null ? nullStr : obj.toString(); + } + + // Comparable + //----------------------------------------------------------------------- + /** + *

Null safe comparison of Comparables.

+ * + * @param type of the values processed by this method + * @param values the set of comparable values, may be null + * @return + *
    + *
  • If any objects are non-null and unequal, the lesser object. + *
  • If all objects are non-null and equal, the first. + *
  • If any of the comparables are null, the lesser of the non-null objects. + *
  • If all the comparables are null, null is returned. + *
+ */ + public static > T min(final T... values) { + T result = null; + if (values != null) { + for (final T value : values) { + if (compare(value, result, true) < 0) { + result = value; + } + } + } + return result; + } + + /** + *

Null safe comparison of Comparables.

+ * + * @param type of the values processed by this method + * @param values the set of comparable values, may be null + * @return + *
    + *
  • If any objects are non-null and unequal, the greater object. + *
  • If all objects are non-null and equal, the first. + *
  • If any of the comparables are null, the greater of the non-null objects. + *
  • If all the comparables are null, null is returned. + *
+ */ +/** + *

Null safe comparison of Comparables.

+ * + * @param + * type of the values processed by this method + * @param values + * the set of comparable values, may be null + * @return
    +
  • If any objects are non-null and unequal, the greater object. +
  • If all objects are non-null and equal, the first. +
  • If any of the comparables are null, the greater of the non-null objects. +
  • If all the comparables are null, null is returned. +
+ */ +public static > T max(final T... values) { + T result = null; + { + for (final T value : /* NPEX_NULL_EXP */ + values) { + if (org.apache.commons.lang3.ObjectUtils.compare(value, result, false) > 0) { + result = value; + } + } + } + return result; +} + + /** + *

Null safe comparison of Comparables. + * {@code null} is assumed to be less than a non-{@code null} value.

+ * + * @param type of the values processed by this method + * @param c1 the first comparable, may be null + * @param c2 the second comparable, may be null + * @return a negative value if c1 < c2, zero if c1 = c2 + * and a positive value if c1 > c2 + */ + public static > int compare(final T c1, final T c2) { + return compare(c1, c2, false); + } + + /** + *

Null safe comparison of Comparables.

+ * + * @param type of the values processed by this method + * @param c1 the first comparable, may be null + * @param c2 the second comparable, may be null + * @param nullGreater if true {@code null} is considered greater + * than a non-{@code null} value or if false {@code null} is + * considered less than a Non-{@code null} value + * @return a negative value if c1 < c2, zero if c1 = c2 + * and a positive value if c1 > c2 + * @see java.util.Comparator#compare(Object, Object) + */ + public static > int compare(final T c1, final T c2, final boolean nullGreater) { + if (c1 == c2) { + return 0; + } else if (c1 == null) { + return nullGreater ? 1 : -1; + } else if (c2 == null) { + return nullGreater ? -1 : 1; + } + return c1.compareTo(c2); + } + + /** + * Find the "best guess" middle value among comparables. If there is an even + * number of total values, the lower of the two middle values will be returned. + * @param type of values processed by this method + * @param items to compare + * @return T at middle position + * @throws NullPointerException if items is {@code null} + * @throws IllegalArgumentException if items is empty or contains {@code null} values + * @since 3.0.1 + */ + public static > T median(final T... items) { + Validate.notEmpty(items); + Validate.noNullElements(items); + final TreeSet sort = new TreeSet(); + Collections.addAll(sort, items); + @SuppressWarnings("unchecked") //we know all items added were T instances + final + T result = (T) sort.toArray()[(sort.size() - 1) / 2]; + return result; + } + + /** + * Find the "best guess" middle value among comparables. If there is an even + * number of total values, the lower of the two middle values will be returned. + * @param type of values processed by this method + * @param comparator to use for comparisons + * @param items to compare + * @return T at middle position + * @throws NullPointerException if items or comparator is {@code null} + * @throws IllegalArgumentException if items is empty or contains {@code null} values + * @since 3.0.1 + */ + public static T median(final Comparator comparator, final T... items) { + Validate.notEmpty(items, "null/empty items"); + Validate.noNullElements(items); + Validate.notNull(comparator, "null comparator"); + final TreeSet sort = new TreeSet(comparator); + Collections.addAll(sort, items); + @SuppressWarnings("unchecked") //we know all items added were T instances + final + T result = (T) sort.toArray()[(sort.size() - 1) / 2]; + return result; + } + + // Mode + //----------------------------------------------------------------------- + /** + * Find the most frequently occurring item. + * + * @param type of values processed by this method + * @param items to check + * @return most populous T, {@code null} if non-unique or no items supplied + * @since 3.0.1 + */ + public static T mode(final T... items) { + if (ArrayUtils.isNotEmpty(items)) { + final HashMap occurrences = new HashMap(items.length); + for (final T t : items) { + final MutableInt count = occurrences.get(t); + if (count == null) { + occurrences.put(t, new MutableInt(1)); + } else { + count.increment(); + } + } + T result = null; + int max = 0; + for (final Map.Entry e : occurrences.entrySet()) { + final int cmp = e.getValue().intValue(); + if (cmp == max) { + result = null; + } else if (cmp > max) { + max = cmp; + result = e.getKey(); + } + } + return result; + } + return null; + } + + // cloning + //----------------------------------------------------------------------- + /** + *

Clone an object.

+ * + * @param the type of the object + * @param obj the object to clone, null returns null + * @return the clone if the object implements {@link Cloneable} otherwise {@code null} + * @throws CloneFailedException if the object is cloneable and the clone operation fails + * @since 3.0 + */ + public static T clone(final T obj) { + if (obj instanceof Cloneable) { + final Object result; + if (obj.getClass().isArray()) { + final Class componentType = obj.getClass().getComponentType(); + if (!componentType.isPrimitive()) { + result = ((Object[]) obj).clone(); + } else { + int length = Array.getLength(obj); + result = Array.newInstance(componentType, length); + while (length-- > 0) { + Array.set(result, length, Array.get(obj, length)); + } + } + } else { + try { + final Method clone = obj.getClass().getMethod("clone"); + result = clone.invoke(obj); + } catch (final NoSuchMethodException e) { + throw new CloneFailedException("Cloneable type " + + obj.getClass().getName() + + " has no clone method", e); + } catch (final IllegalAccessException e) { + throw new CloneFailedException("Cannot clone Cloneable type " + + obj.getClass().getName(), e); + } catch (final InvocationTargetException e) { + throw new CloneFailedException("Exception cloning Cloneable type " + + obj.getClass().getName(), e.getCause()); + } + } + @SuppressWarnings("unchecked") // OK because input is of type T + final T checked = (T) result; + return checked; + } + + return null; + } + + /** + *

Clone an object if possible.

+ * + *

This method is similar to {@link #clone(Object)}, but will return the provided + * instance as the return value instead of {@code null} if the instance + * is not cloneable. This is more convenient if the caller uses different + * implementations (e.g. of a service) and some of the implementations do not allow concurrent + * processing or have state. In such cases the implementation can simply provide a proper + * clone implementation and the caller's code does not have to change.

+ * + * @param the type of the object + * @param obj the object to clone, null returns null + * @return the clone if the object implements {@link Cloneable} otherwise the object itself + * @throws CloneFailedException if the object is cloneable and the clone operation fails + * @since 3.0 + */ + public static T cloneIfPossible(final T obj) { + final T clone = clone(obj); + return clone == null ? obj : clone; + } + + // Null + //----------------------------------------------------------------------- + /** + *

Class used as a null placeholder where {@code null} + * has another meaning.

+ * + *

For example, in a {@code HashMap} the + * {@link java.util.HashMap#get(java.lang.Object)} method returns + * {@code null} if the {@code Map} contains {@code null} or if there is + * no matching key. The {@code Null} placeholder can be used to distinguish + * between these two cases.

+ * + *

Another example is {@code Hashtable}, where {@code null} + * cannot be stored.

+ */ + public static class Null implements Serializable { + /** + * Required for serialization support. Declare serialization compatibility with Commons Lang 1.0 + * + * @see java.io.Serializable + */ + private static final long serialVersionUID = 7092611880189329093L; + + /** + * Restricted constructor - singleton. + */ + Null() { + super(); + } + + /** + *

Ensure singleton.

+ * + * @return the singleton value + */ + private Object readResolve() { + return ObjectUtils.NULL; + } + } + + + // Constants (LANG-816): + /* + These methods ensure constants are not inlined by javac. + For example, typically a developer might declare a constant like so: + + public final static int MAGIC_NUMBER = 5; + + Should a different jar file refer to this, and the MAGIC_NUMBER + is changed a later date (e.g., MAGIC_NUMBER = 6), the different jar + file will need to recompile itself. This is because javac + typically inlines the primitive or String constant directly into + the bytecode, and removes the reference to the MAGIC_NUMBER field. + + To help the other jar (so that it does not need to recompile + when constants are changed) the original developer can declare + their constant using one of the CONST() utility methods, instead: + + public final static int MAGIC_NUMBER = CONST(5); + */ + + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static boolean MAGIC_FLAG = ObjectUtils.CONST(true);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the boolean value to return + * @return the boolean v, unchanged + * @since 3.2 + */ + public static boolean CONST(final boolean v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static byte MAGIC_BYTE = ObjectUtils.CONST((byte) 127);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the byte value to return + * @return the byte v, unchanged + * @since 3.2 + */ + public static byte CONST(final byte v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static byte MAGIC_BYTE = ObjectUtils.CONST_BYTE(127);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the byte literal (as an int) value to return + * @throws IllegalArgumentException if the value passed to v + * is larger than a byte, that is, smaller than -128 or + * larger than 127. + * @return the byte v, unchanged + * @since 3.2 + */ + public static byte CONST_BYTE(final int v) throws IllegalArgumentException { + if (v < Byte.MIN_VALUE || v > Byte.MAX_VALUE) { + throw new IllegalArgumentException("Supplied value must be a valid byte literal between -128 and 127: [" + v + "]"); + } + return (byte) v; + } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static char MAGIC_CHAR = ObjectUtils.CONST('a');
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the char value to return + * @return the char v, unchanged + * @since 3.2 + */ + public static char CONST(final char v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static short MAGIC_SHORT = ObjectUtils.CONST((short) 123);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the short value to return + * @return the short v, unchanged + * @since 3.2 + */ + public static short CONST(final short v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static short MAGIC_SHORT = ObjectUtils.CONST_SHORT(127);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the short literal (as an int) value to return + * @throws IllegalArgumentException if the value passed to v + * is larger than a short, that is, smaller than -32768 or + * larger than 32767. + * @return the byte v, unchanged + * @since 3.2 + */ + public static short CONST_SHORT(final int v) throws IllegalArgumentException { + if (v < Short.MIN_VALUE || v > Short.MAX_VALUE) { + throw new IllegalArgumentException("Supplied value must be a valid byte literal between -32768 and 32767: [" + v + "]"); + } + return (short) v; + } + + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static int MAGIC_INT = ObjectUtils.CONST(123);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the int value to return + * @return the int v, unchanged + * @since 3.2 + */ + public static int CONST(final int v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static long MAGIC_LONG = ObjectUtils.CONST(123L);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the long value to return + * @return the long v, unchanged + * @since 3.2 + */ + public static long CONST(final long v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static float MAGIC_FLOAT = ObjectUtils.CONST(1.0f);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the float value to return + * @return the float v, unchanged + * @since 3.2 + */ + public static float CONST(final float v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static double MAGIC_DOUBLE = ObjectUtils.CONST(1.0);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the double value to return + * @return the double v, unchanged + * @since 3.2 + */ + public static double CONST(final double v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static String MAGIC_STRING = ObjectUtils.CONST("abc");
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param the Object type + * @param v the genericized Object value to return (typically a String). + * @return the genericized Object v, unchanged (typically a String). + * @since 3.2 + */ + public static T CONST(final T v) { return v; } + +} diff --git a/Java/commons-lang-ObjectUtils_528/metadata.json b/Java/commons-lang-ObjectUtils_528/metadata.json new file mode 100644 index 000000000..863f5f6ea --- /dev/null +++ b/Java/commons-lang-ObjectUtils_528/metadata.json @@ -0,0 +1,21 @@ +{ + "language": "java", + "id": "commons-lang-ObjectUtils_528", + "buggyPath": ".", + "referencePath": null, + "buildCommand": "mvn package -V -B -Denforcer.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true -Drat.skip=true -Dlicense.skip=true -Dfindbugs.skip=true -Dgpg.skip=true -Dskip.npm=true -Dskip.gulp=true -Dskip.bower=true -Drat.numUnapprovedLicenses=100 -DskipTests=true -DskipITs=true -Dtest=None -DfailIfNoTests=false", + "testCommand": "mvn test -V -B -Denforcer.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true -Drat.skip=true -Dlicense.skip=true -Dfindbugs.skip=true -Dgpg.skip=true -Dskip.npm=true -Dskip.gulp=true -Dskip.bower=true -Drat.numUnapprovedLicenses=100", + "categories": [ + "safety", + "npe" + ], + "npe": { + "filepath": "src/main/java/org/apache/commons/lang3/ObjectUtils.java", + "line": 544, + "npe_method": "max", + "deref_field": "values", + "npe_class": "ObjectUtils", + "repo": "commons-lang", + "bug_id": "ObjectUtils_528" + } +} diff --git a/Java/commons-lang-ObjectUtils_528/npe.json b/Java/commons-lang-ObjectUtils_528/npe.json new file mode 100644 index 000000000..be6e65f55 --- /dev/null +++ b/Java/commons-lang-ObjectUtils_528/npe.json @@ -0,0 +1,7 @@ +{ + "filepath": "src/main/java/org/apache/commons/lang3/ObjectUtils.java", + "line": 544, + "npe_method": "max", + "deref_field": "values", + "npe_class": "ObjectUtils" +} \ No newline at end of file diff --git a/Java/commons-lang-ObjectUtils_635/Dockerfile b/Java/commons-lang-ObjectUtils_635/Dockerfile new file mode 100644 index 000000000..7b7fbe349 --- /dev/null +++ b/Java/commons-lang-ObjectUtils_635/Dockerfile @@ -0,0 +1,18 @@ +FROM ghcr.io/kupl/starlab-benchmarks/java-base:commons-lang + +ENV TZ=Asia/Seoul + +COPY ./metadata.json . +COPY ./npe.json . +COPY ./buggy.java /tmp/buggy.java +RUN export BUGGY_PATH=$(cat metadata.json | jq -r ".npe.filepath") \ + && export BUGGY_LINE=$(cat metadata.json | jq -r ".npe.line") \ + && export BUGGY_MTHD=$(cat metadata.json | jq -r ".npe.npe_method") \ + && mv /tmp/buggy.java $BUGGY_PATH \ + && echo "[{\"filepath\": \"$BUGGY_PATH\", \"line\": $BUGGY_LINE, \"method_name\": \"$BUGGY_MTHD\"}]" | jq . > traces.json + +RUN git init . && git add -A + +RUN $(cat metadata.json | jq -r ".buildCommand") + +RUN $(cat metadata.json | jq -r ".testCommand"); if [ $? -eq 0 ]; then exit 1; fi diff --git a/Java/commons-lang-ObjectUtils_635/buggy.java b/Java/commons-lang-ObjectUtils_635/buggy.java new file mode 100644 index 000000000..fd1299b3b --- /dev/null +++ b/Java/commons-lang-ObjectUtils_635/buggy.java @@ -0,0 +1,1027 @@ +/* + * 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.Serializable; +import java.lang.reflect.Array; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.Map; +import java.util.TreeSet; + +import org.apache.commons.lang3.exception.CloneFailedException; +import org.apache.commons.lang3.mutable.MutableInt; +import org.apache.commons.lang3.text.StrBuilder; + +/** + *

Operations on {@code Object}.

+ * + *

This class tries to handle {@code null} input gracefully. + * An exception will generally not be thrown for a {@code null} input. + * Each method documents its behaviour in more detail.

+ * + *

#ThreadSafe#

+ * @since 1.0 + */ +//@Immutable +public class ObjectUtils { + + /** + *

Singleton used as a {@code null} placeholder where + * {@code null} has another meaning.

+ * + *

For example, in a {@code HashMap} the + * {@link java.util.HashMap#get(java.lang.Object)} method returns + * {@code null} if the {@code Map} contains {@code null} or if there + * is no matching key. The {@code Null} placeholder can be used to + * distinguish between these two cases.

+ * + *

Another example is {@code Hashtable}, where {@code null} + * cannot be stored.

+ * + *

This instance is Serializable.

+ */ + public static final Null NULL = new Null(); + + /** + *

{@code ObjectUtils} instances should NOT be constructed in + * standard programming. Instead, the static methods on the class should + * be used, such as {@code ObjectUtils.defaultIfNull("a","b");}.

+ * + *

This constructor is public to permit tools that require a JavaBean + * instance to operate.

+ */ + public ObjectUtils() { + super(); + } + + // Defaulting + //----------------------------------------------------------------------- + /** + *

Returns a default value if the object passed is {@code null}.

+ * + *
+     * ObjectUtils.defaultIfNull(null, null)      = null
+     * ObjectUtils.defaultIfNull(null, "")        = ""
+     * ObjectUtils.defaultIfNull(null, "zz")      = "zz"
+     * ObjectUtils.defaultIfNull("abc", *)        = "abc"
+     * ObjectUtils.defaultIfNull(Boolean.TRUE, *) = Boolean.TRUE
+     * 
+ * + * @param the type of the object + * @param object the {@code Object} to test, may be {@code null} + * @param defaultValue the default value to return, may be {@code null} + * @return {@code object} if it is not {@code null}, defaultValue otherwise + */ + public static T defaultIfNull(final T object, final T defaultValue) { + return object != null ? object : defaultValue; + } + + /** + *

Returns the first value in the array which is not {@code null}. + * If all the values are {@code null} or the array is {@code null} + * or empty then {@code null} is returned.

+ * + *
+     * ObjectUtils.firstNonNull(null, null)      = null
+     * ObjectUtils.firstNonNull(null, "")        = ""
+     * ObjectUtils.firstNonNull(null, null, "")  = ""
+     * ObjectUtils.firstNonNull(null, "zz")      = "zz"
+     * ObjectUtils.firstNonNull("abc", *)        = "abc"
+     * ObjectUtils.firstNonNull(null, "xyz", *)  = "xyz"
+     * ObjectUtils.firstNonNull(Boolean.TRUE, *) = Boolean.TRUE
+     * ObjectUtils.firstNonNull()                = null
+     * 
+ * + * @param the component type of the array + * @param values the values to test, may be {@code null} or empty + * @return the first value from {@code values} which is not {@code null}, + * or {@code null} if there are no non-null values + * @since 3.0 + */ + public static T firstNonNull(final T... values) { + if (values != null) { + for (final T val : values) { + if (val != null) { + return val; + } + } + } + return null; + } + + /** + * Checks if any value in the given array is not {@code null}. + * + *

+ * If all the values are {@code null} or the array is {@code null} + * or empty then {@code false} is returned. Otherwise {@code true} is returned. + *

+ * + *
+     * ObjectUtils.anyNotNull(*)                = true
+     * ObjectUtils.anyNotNull(*, null)          = true
+     * ObjectUtils.anyNotNull(null, *)          = true
+     * ObjectUtils.anyNotNull(null, null, *, *) = true
+     * ObjectUtils.anyNotNull(null)             = false
+     * ObjectUtils.anyNotNull(null, null)       = false
+     * 
+ * + * @param values the values to test, may be {@code null} or empty + * @return {@code true} if there is at least one non-null value in the array, + * {@code false} if all values in the array are {@code null}s. + * If the array is {@code null} or empty {@code false} is also returned. + * @since 3.5 + */ + public static boolean anyNotNull(final Object... values) { + return firstNonNull(values) != null; + } + + /** + * Checks if all values in the array are not {@code nulls}. + * + *

+ * If any value is {@code null} or the array is {@code null} then + * {@code false} is returned. If all elements in array are not + * {@code null} or the array is empty (contains no elements) {@code true} + * is returned. + *

+ * + *
+     * ObjectUtils.allNotNull(*)             = true
+     * ObjectUtils.allNotNull(*, *)          = true
+     * ObjectUtils.allNotNull(null)          = false
+     * ObjectUtils.allNotNull(null, null)    = false
+     * ObjectUtils.allNotNull(null, *)       = false
+     * ObjectUtils.allNotNull(*, null)       = false
+     * ObjectUtils.allNotNull(*, *, null, *) = false
+     * 
+ * + * @param values the values to test, may be {@code null} or empty + * @return {@code false} if there is at least one {@code null} value in the array or the array is {@code null}, + * {@code true} if all values in the array are not {@code null}s or array contains no elements. + * @since 3.5 + */ + public static boolean allNotNull(final Object... values) { + if (values == null) { + return false; + } + + for (final Object val : values) { + if (val == null) { + return false; + } + } + + return true; + } + + // Null-safe equals/hashCode + //----------------------------------------------------------------------- + /** + *

Compares two objects for equality, where either one or both + * objects may be {@code null}.

+ * + *
+     * ObjectUtils.equals(null, null)                  = true
+     * ObjectUtils.equals(null, "")                    = false
+     * ObjectUtils.equals("", null)                    = false
+     * ObjectUtils.equals("", "")                      = true
+     * ObjectUtils.equals(Boolean.TRUE, null)          = false
+     * ObjectUtils.equals(Boolean.TRUE, "true")        = false
+     * ObjectUtils.equals(Boolean.TRUE, Boolean.TRUE)  = true
+     * ObjectUtils.equals(Boolean.TRUE, Boolean.FALSE) = false
+     * 
+ * + * @param object1 the first object, may be {@code null} + * @param object2 the second object, may be {@code null} + * @return {@code true} if the values of both objects are the same + * @deprecated this method has been replaced by {@code java.util.Objects.equals(Object, Object)} in Java 7 and will + * be removed from future releases. + */ + @Deprecated + public static boolean equals(final Object object1, final Object object2) { + if (object1 == object2) { + return true; + } + if (object1 == null || object2 == null) { + return false; + } + return object1.equals(object2); + } + + /** + *

Compares two objects for inequality, where either one or both + * objects may be {@code null}.

+ * + *
+     * ObjectUtils.notEqual(null, null)                  = false
+     * ObjectUtils.notEqual(null, "")                    = true
+     * ObjectUtils.notEqual("", null)                    = true
+     * ObjectUtils.notEqual("", "")                      = false
+     * ObjectUtils.notEqual(Boolean.TRUE, null)          = true
+     * ObjectUtils.notEqual(Boolean.TRUE, "true")        = true
+     * ObjectUtils.notEqual(Boolean.TRUE, Boolean.TRUE)  = false
+     * ObjectUtils.notEqual(Boolean.TRUE, Boolean.FALSE) = true
+     * 
+ * + * @param object1 the first object, may be {@code null} + * @param object2 the second object, may be {@code null} + * @return {@code false} if the values of both objects are the same + */ + public static boolean notEqual(final Object object1, final Object object2) { + return ObjectUtils.equals(object1, object2) == false; + } + + /** + *

Gets the hash code of an object returning zero when the + * object is {@code null}.

+ * + *
+     * ObjectUtils.hashCode(null)   = 0
+     * ObjectUtils.hashCode(obj)    = obj.hashCode()
+     * 
+ * + * @param obj the object to obtain the hash code of, may be {@code null} + * @return the hash code of the object, or zero if null + * @since 2.1 + * @deprecated this method has been replaced by {@code java.util.Objects.hashCode(Object)} in Java 7 and will be + * removed in future releases + */ + @Deprecated + public static int hashCode(final Object obj) { + // hashCode(Object) retained for performance, as hash code is often critical + return obj == null ? 0 : obj.hashCode(); + } + + /** + *

Gets the hash code for multiple objects.

+ * + *

This allows a hash code to be rapidly calculated for a number of objects. + * The hash code for a single object is the not same as {@link #hashCode(Object)}. + * The hash code for multiple objects is the same as that calculated by an + * {@code ArrayList} containing the specified objects.

+ * + *
+     * ObjectUtils.hashCodeMulti()                 = 1
+     * ObjectUtils.hashCodeMulti((Object[]) null)  = 1
+     * ObjectUtils.hashCodeMulti(a)                = 31 + a.hashCode()
+     * ObjectUtils.hashCodeMulti(a,b)              = (31 + a.hashCode()) * 31 + b.hashCode()
+     * ObjectUtils.hashCodeMulti(a,b,c)            = ((31 + a.hashCode()) * 31 + b.hashCode()) * 31 + c.hashCode()
+     * 
+ * + * @param objects the objects to obtain the hash code of, may be {@code null} + * @return the hash code of the objects, or zero if null + * @since 3.0 + * @deprecated this method has been replaced by {@code java.util.Objects.hash(Object...)} in Java 7 and will be + * removed in future releases. + */ + @Deprecated + public static int hashCodeMulti(final Object... objects) { + int hash = 1; + if (objects != null) { + for (final Object object : objects) { + final int tmpHash = ObjectUtils.hashCode(object); + hash = hash * 31 + tmpHash; + } + } + return hash; + } + + // Identity ToString + //----------------------------------------------------------------------- + /** + *

Gets the toString that would be produced by {@code Object} + * if a class did not override toString itself. {@code null} + * will return {@code null}.

+ * + *
+     * ObjectUtils.identityToString(null)         = null
+     * ObjectUtils.identityToString("")           = "java.lang.String@1e23"
+     * ObjectUtils.identityToString(Boolean.TRUE) = "java.lang.Boolean@7fa"
+     * 
+ * + * @param object the object to create a toString for, may be + * {@code null} + * @return the default toString text, or {@code null} if + * {@code null} passed in + */ + public static String identityToString(final Object object) { + if (object == null) { + return null; + } + final StringBuilder builder = new StringBuilder(); + identityToString(builder, object); + return builder.toString(); + } + + /** + *

Appends the toString that would be produced by {@code Object} + * if a class did not override toString itself. {@code null} + * will throw a NullPointerException for either of the two parameters.

+ * + *
+     * ObjectUtils.identityToString(appendable, "")            = appendable.append("java.lang.String@1e23"
+     * ObjectUtils.identityToString(appendable, Boolean.TRUE)  = appendable.append("java.lang.Boolean@7fa"
+     * ObjectUtils.identityToString(appendable, Boolean.TRUE)  = appendable.append("java.lang.Boolean@7fa")
+     * 
+ * + * @param appendable the appendable to append to + * @param object the object to create a toString for + * @throws IOException if an I/O error occurs + * @since 3.2 + */ + public static void identityToString(final Appendable appendable, final Object object) throws IOException { + if (object == null) { + throw new NullPointerException("Cannot get the toString of a null identity"); + } + appendable.append(object.getClass().getName()) + .append('@') + .append(Integer.toHexString(System.identityHashCode(object))); + } + + /** + *

Appends the toString that would be produced by {@code Object} + * if a class did not override toString itself. {@code null} + * will throw a NullPointerException for either of the two parameters.

+ * + *
+     * ObjectUtils.identityToString(builder, "")            = builder.append("java.lang.String@1e23"
+     * ObjectUtils.identityToString(builder, Boolean.TRUE)  = builder.append("java.lang.Boolean@7fa"
+     * ObjectUtils.identityToString(builder, Boolean.TRUE)  = builder.append("java.lang.Boolean@7fa")
+     * 
+ * + * @param builder the builder to append to + * @param object the object to create a toString for + * @since 3.2 + */ + public static void identityToString(final StrBuilder builder, final Object object) { + if (object == null) { + throw new NullPointerException("Cannot get the toString of a null identity"); + } + builder.append(object.getClass().getName()) + .append('@') + .append(Integer.toHexString(System.identityHashCode(object))); + } + + /** + *

Appends the toString that would be produced by {@code Object} + * if a class did not override toString itself. {@code null} + * will throw a NullPointerException for either of the two parameters.

+ * + *
+     * ObjectUtils.identityToString(buf, "")            = buf.append("java.lang.String@1e23"
+     * ObjectUtils.identityToString(buf, Boolean.TRUE)  = buf.append("java.lang.Boolean@7fa"
+     * ObjectUtils.identityToString(buf, Boolean.TRUE)  = buf.append("java.lang.Boolean@7fa")
+     * 
+ * + * @param buffer the buffer to append to + * @param object the object to create a toString for + * @since 2.4 + */ + public static void identityToString(final StringBuffer buffer, final Object object) { + if (object == null) { + throw new NullPointerException("Cannot get the toString of a null identity"); + } + buffer.append(object.getClass().getName()) + .append('@') + .append(Integer.toHexString(System.identityHashCode(object))); + } + + /** + *

Appends the toString that would be produced by {@code Object} + * if a class did not override toString itself. {@code null} + * will throw a NullPointerException for either of the two parameters.

+ * + *
+     * ObjectUtils.identityToString(builder, "")            = builder.append("java.lang.String@1e23"
+     * ObjectUtils.identityToString(builder, Boolean.TRUE)  = builder.append("java.lang.Boolean@7fa"
+     * ObjectUtils.identityToString(builder, Boolean.TRUE)  = builder.append("java.lang.Boolean@7fa")
+     * 
+ * + * @param builder the builder to append to + * @param object the object to create a toString for + * @since 3.2 + */ + public static void identityToString(final StringBuilder builder, final Object object) { + if (object == null) { + throw new NullPointerException("Cannot get the toString of a null identity"); + } + builder.append(object.getClass().getName()) + .append('@') + .append(Integer.toHexString(System.identityHashCode(object))); + } + + // ToString + //----------------------------------------------------------------------- + /** + *

Gets the {@code toString} of an {@code Object} returning + * an empty string ("") if {@code null} input.

+ * + *
+     * ObjectUtils.toString(null)         = ""
+     * ObjectUtils.toString("")           = ""
+     * ObjectUtils.toString("bat")        = "bat"
+     * ObjectUtils.toString(Boolean.TRUE) = "true"
+     * 
+ * + * @see StringUtils#defaultString(String) + * @see String#valueOf(Object) + * @param obj the Object to {@code toString}, may be null + * @return the passed in Object's toString, or {@code ""} if {@code null} input + * @since 2.0 + * @deprecated this method has been replaced by {@code java.util.Objects.toString(Object)} in Java 7 and will be + * removed in future releases. Note however that said method will return "null" for null references, while this + * method returns and empty String. To preserve behavior use {@code java.util.Objects.toString(myObject, "")} + */ + @Deprecated + public static String toString(final Object obj) { + return obj == null ? StringUtils.EMPTY : obj.toString(); + } + + /** + *

Gets the {@code toString} of an {@code Object} returning + * a specified text if {@code null} input.

+ * + *
+     * ObjectUtils.toString(null, null)           = null
+     * ObjectUtils.toString(null, "null")         = "null"
+     * ObjectUtils.toString("", "null")           = ""
+     * ObjectUtils.toString("bat", "null")        = "bat"
+     * ObjectUtils.toString(Boolean.TRUE, "null") = "true"
+     * 
+ * + * @see StringUtils#defaultString(String,String) + * @see String#valueOf(Object) + * @param obj the Object to {@code toString}, may be null + * @param nullStr the String to return if {@code null} input, may be null + * @return the passed in Object's toString, or {@code nullStr} if {@code null} input + * @since 2.0 + * @deprecated this method has been replaced by {@code java.util.Objects.toString(Object, String)} in Java 7 and + * will be removed in future releases. + */ + @Deprecated + public static String toString(final Object obj, final String nullStr) { + return obj == null ? nullStr : obj.toString(); + } + + // Comparable + //----------------------------------------------------------------------- + /** + *

Null safe comparison of Comparables.

+ * + * @param type of the values processed by this method + * @param values the set of comparable values, may be null + * @return + *
    + *
  • If any objects are non-null and unequal, the lesser object. + *
  • If all objects are non-null and equal, the first. + *
  • If any of the comparables are null, the lesser of the non-null objects. + *
  • If all the comparables are null, null is returned. + *
+ */ + public static > T min(final T... values) { + T result = null; + if (values != null) { + for (final T value : values) { + if (compare(value, result, true) < 0) { + result = value; + } + } + } + return result; + } + + /** + *

Null safe comparison of Comparables.

+ * + * @param type of the values processed by this method + * @param values the set of comparable values, may be null + * @return + *
    + *
  • If any objects are non-null and unequal, the greater object. + *
  • If all objects are non-null and equal, the first. + *
  • If any of the comparables are null, the greater of the non-null objects. + *
  • If all the comparables are null, null is returned. + *
+ */ + public static > T max(final T... values) { + T result = null; + if (values != null) { + for (final T value : values) { + if (compare(value, result, false) > 0) { + result = value; + } + } + } + return result; + } + + /** + *

Null safe comparison of Comparables. + * {@code null} is assumed to be less than a non-{@code null} value.

+ * + * @param type of the values processed by this method + * @param c1 the first comparable, may be null + * @param c2 the second comparable, may be null + * @return a negative value if c1 < c2, zero if c1 = c2 + * and a positive value if c1 > c2 + */ + public static > int compare(final T c1, final T c2) { + return compare(c1, c2, false); + } + + /** + *

Null safe comparison of Comparables.

+ * + * @param type of the values processed by this method + * @param c1 the first comparable, may be null + * @param c2 the second comparable, may be null + * @param nullGreater if true {@code null} is considered greater + * than a non-{@code null} value or if false {@code null} is + * considered less than a Non-{@code null} value + * @return a negative value if c1 < c2, zero if c1 = c2 + * and a positive value if c1 > c2 + * @see java.util.Comparator#compare(Object, Object) + */ + public static > int compare(final T c1, final T c2, final boolean nullGreater) { + if (c1 == c2) { + return 0; + } else if (c1 == null) { + return nullGreater ? 1 : -1; + } else if (c2 == null) { + return nullGreater ? -1 : 1; + } + return c1.compareTo(c2); + } + + /** + * Find the "best guess" middle value among comparables. If there is an even + * number of total values, the lower of the two middle values will be returned. + * @param type of values processed by this method + * @param items to compare + * @return T at middle position + * @throws NullPointerException if items is {@code null} + * @throws IllegalArgumentException if items is empty or contains {@code null} values + * @since 3.0.1 + */ + public static > T median(final T... items) { + Validate.notEmpty(items); + Validate.noNullElements(items); + final TreeSet sort = new TreeSet(); + Collections.addAll(sort, items); + @SuppressWarnings("unchecked") //we know all items added were T instances + final + T result = (T) sort.toArray()[(sort.size() - 1) / 2]; + return result; + } + + /** + * Find the "best guess" middle value among comparables. If there is an even + * number of total values, the lower of the two middle values will be returned. + * @param type of values processed by this method + * @param comparator to use for comparisons + * @param items to compare + * @return T at middle position + * @throws NullPointerException if items or comparator is {@code null} + * @throws IllegalArgumentException if items is empty or contains {@code null} values + * @since 3.0.1 + */ + public static T median(final Comparator comparator, final T... items) { + Validate.notEmpty(items, "null/empty items"); + Validate.noNullElements(items); + Validate.notNull(comparator, "null comparator"); + final TreeSet sort = new TreeSet(comparator); + Collections.addAll(sort, items); + @SuppressWarnings("unchecked") //we know all items added were T instances + final + T result = (T) sort.toArray()[(sort.size() - 1) / 2]; + return result; + } + + // Mode + //----------------------------------------------------------------------- + /** + * Find the most frequently occurring item. + * + * @param type of values processed by this method + * @param items to check + * @return most populous T, {@code null} if non-unique or no items supplied + * @since 3.0.1 + */ +// Mode +// ----------------------------------------------------------------------- +/** + * Find the most frequently occurring item. + * + * @param + * type of values processed by this method + * @param items + * to check + * @return most populous T, {@code null} if non-unique or no items supplied + * @since 3.0.1 + */ +public static T mode(final T... items) { + if (org.apache.commons.lang3.ArrayUtils.isNotEmpty(items)) { + final java.util.HashMap occurrences = new java.util.HashMap(items.length); + for (final T t : items) { + final org.apache.commons.lang3.mutable.MutableInt count = occurrences.get(t); + { + /* NPEX_NULL_EXP */ + count.increment(); + } + } + T result = null; + int max = 0; + for (final java.util.Map.Entry e : occurrences.entrySet()) { + final int cmp = e.getValue().intValue(); + if (cmp == max) { + result = null; + } else if (cmp > max) { + max = cmp; + result = e.getKey(); + } + } + return result; + } + return null; +} + + // cloning + //----------------------------------------------------------------------- + /** + *

Clone an object.

+ * + * @param the type of the object + * @param obj the object to clone, null returns null + * @return the clone if the object implements {@link Cloneable} otherwise {@code null} + * @throws CloneFailedException if the object is cloneable and the clone operation fails + * @since 3.0 + */ + public static T clone(final T obj) { + if (obj instanceof Cloneable) { + final Object result; + if (obj.getClass().isArray()) { + final Class componentType = obj.getClass().getComponentType(); + if (!componentType.isPrimitive()) { + result = ((Object[]) obj).clone(); + } else { + int length = Array.getLength(obj); + result = Array.newInstance(componentType, length); + while (length-- > 0) { + Array.set(result, length, Array.get(obj, length)); + } + } + } else { + try { + final Method clone = obj.getClass().getMethod("clone"); + result = clone.invoke(obj); + } catch (final NoSuchMethodException e) { + throw new CloneFailedException("Cloneable type " + + obj.getClass().getName() + + " has no clone method", e); + } catch (final IllegalAccessException e) { + throw new CloneFailedException("Cannot clone Cloneable type " + + obj.getClass().getName(), e); + } catch (final InvocationTargetException e) { + throw new CloneFailedException("Exception cloning Cloneable type " + + obj.getClass().getName(), e.getCause()); + } + } + @SuppressWarnings("unchecked") // OK because input is of type T + final T checked = (T) result; + return checked; + } + + return null; + } + + /** + *

Clone an object if possible.

+ * + *

This method is similar to {@link #clone(Object)}, but will return the provided + * instance as the return value instead of {@code null} if the instance + * is not cloneable. This is more convenient if the caller uses different + * implementations (e.g. of a service) and some of the implementations do not allow concurrent + * processing or have state. In such cases the implementation can simply provide a proper + * clone implementation and the caller's code does not have to change.

+ * + * @param the type of the object + * @param obj the object to clone, null returns null + * @return the clone if the object implements {@link Cloneable} otherwise the object itself + * @throws CloneFailedException if the object is cloneable and the clone operation fails + * @since 3.0 + */ + public static T cloneIfPossible(final T obj) { + final T clone = clone(obj); + return clone == null ? obj : clone; + } + + // Null + //----------------------------------------------------------------------- + /** + *

Class used as a null placeholder where {@code null} + * has another meaning.

+ * + *

For example, in a {@code HashMap} the + * {@link java.util.HashMap#get(java.lang.Object)} method returns + * {@code null} if the {@code Map} contains {@code null} or if there is + * no matching key. The {@code Null} placeholder can be used to distinguish + * between these two cases.

+ * + *

Another example is {@code Hashtable}, where {@code null} + * cannot be stored.

+ */ + public static class Null implements Serializable { + /** + * Required for serialization support. Declare serialization compatibility with Commons Lang 1.0 + * + * @see java.io.Serializable + */ + private static final long serialVersionUID = 7092611880189329093L; + + /** + * Restricted constructor - singleton. + */ + Null() { + super(); + } + + /** + *

Ensure singleton.

+ * + * @return the singleton value + */ + private Object readResolve() { + return ObjectUtils.NULL; + } + } + + + // Constants (LANG-816): + /* + These methods ensure constants are not inlined by javac. + For example, typically a developer might declare a constant like so: + + public final static int MAGIC_NUMBER = 5; + + Should a different jar file refer to this, and the MAGIC_NUMBER + is changed a later date (e.g., MAGIC_NUMBER = 6), the different jar + file will need to recompile itself. This is because javac + typically inlines the primitive or String constant directly into + the bytecode, and removes the reference to the MAGIC_NUMBER field. + + To help the other jar (so that it does not need to recompile + when constants are changed) the original developer can declare + their constant using one of the CONST() utility methods, instead: + + public final static int MAGIC_NUMBER = CONST(5); + */ + + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static boolean MAGIC_FLAG = ObjectUtils.CONST(true);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the boolean value to return + * @return the boolean v, unchanged + * @since 3.2 + */ + public static boolean CONST(final boolean v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static byte MAGIC_BYTE = ObjectUtils.CONST((byte) 127);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the byte value to return + * @return the byte v, unchanged + * @since 3.2 + */ + public static byte CONST(final byte v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static byte MAGIC_BYTE = ObjectUtils.CONST_BYTE(127);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the byte literal (as an int) value to return + * @throws IllegalArgumentException if the value passed to v + * is larger than a byte, that is, smaller than -128 or + * larger than 127. + * @return the byte v, unchanged + * @since 3.2 + */ + public static byte CONST_BYTE(final int v) throws IllegalArgumentException { + if (v < Byte.MIN_VALUE || v > Byte.MAX_VALUE) { + throw new IllegalArgumentException("Supplied value must be a valid byte literal between -128 and 127: [" + v + "]"); + } + return (byte) v; + } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static char MAGIC_CHAR = ObjectUtils.CONST('a');
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the char value to return + * @return the char v, unchanged + * @since 3.2 + */ + public static char CONST(final char v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static short MAGIC_SHORT = ObjectUtils.CONST((short) 123);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the short value to return + * @return the short v, unchanged + * @since 3.2 + */ + public static short CONST(final short v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static short MAGIC_SHORT = ObjectUtils.CONST_SHORT(127);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the short literal (as an int) value to return + * @throws IllegalArgumentException if the value passed to v + * is larger than a short, that is, smaller than -32768 or + * larger than 32767. + * @return the byte v, unchanged + * @since 3.2 + */ + public static short CONST_SHORT(final int v) throws IllegalArgumentException { + if (v < Short.MIN_VALUE || v > Short.MAX_VALUE) { + throw new IllegalArgumentException("Supplied value must be a valid byte literal between -32768 and 32767: [" + v + "]"); + } + return (short) v; + } + + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static int MAGIC_INT = ObjectUtils.CONST(123);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the int value to return + * @return the int v, unchanged + * @since 3.2 + */ + public static int CONST(final int v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static long MAGIC_LONG = ObjectUtils.CONST(123L);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the long value to return + * @return the long v, unchanged + * @since 3.2 + */ + public static long CONST(final long v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static float MAGIC_FLOAT = ObjectUtils.CONST(1.0f);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the float value to return + * @return the float v, unchanged + * @since 3.2 + */ + public static float CONST(final float v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static double MAGIC_DOUBLE = ObjectUtils.CONST(1.0);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the double value to return + * @return the double v, unchanged + * @since 3.2 + */ + public static double CONST(final double v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static String MAGIC_STRING = ObjectUtils.CONST("abc");
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param the Object type + * @param v the genericized Object value to return (typically a String). + * @return the genericized Object v, unchanged (typically a String). + * @since 3.2 + */ + public static T CONST(final T v) { return v; } + +} diff --git a/Java/commons-lang-ObjectUtils_635/metadata.json b/Java/commons-lang-ObjectUtils_635/metadata.json new file mode 100644 index 000000000..0253a84c4 --- /dev/null +++ b/Java/commons-lang-ObjectUtils_635/metadata.json @@ -0,0 +1,21 @@ +{ + "language": "java", + "id": "commons-lang-ObjectUtils_635", + "buggyPath": ".", + "referencePath": null, + "buildCommand": "mvn package -V -B -Denforcer.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true -Drat.skip=true -Dlicense.skip=true -Dfindbugs.skip=true -Dgpg.skip=true -Dskip.npm=true -Dskip.gulp=true -Dskip.bower=true -Drat.numUnapprovedLicenses=100 -DskipTests=true -DskipITs=true -Dtest=None -DfailIfNoTests=false", + "testCommand": "mvn test -V -B -Denforcer.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true -Drat.skip=true -Dlicense.skip=true -Dfindbugs.skip=true -Dgpg.skip=true -Dskip.npm=true -Dskip.gulp=true -Dskip.bower=true -Drat.numUnapprovedLicenses=100", + "categories": [ + "safety", + "npe" + ], + "npe": { + "filepath": "src/main/java/org/apache/commons/lang3/ObjectUtils.java", + "line": 649, + "npe_method": "mode", + "deref_field": "count", + "npe_class": "ObjectUtils", + "repo": "commons-lang", + "bug_id": "ObjectUtils_635" + } +} diff --git a/Java/commons-lang-ObjectUtils_635/npe.json b/Java/commons-lang-ObjectUtils_635/npe.json new file mode 100644 index 000000000..efa546218 --- /dev/null +++ b/Java/commons-lang-ObjectUtils_635/npe.json @@ -0,0 +1,7 @@ +{ + "filepath": "src/main/java/org/apache/commons/lang3/ObjectUtils.java", + "line": 649, + "npe_method": "mode", + "deref_field": "count", + "npe_class": "ObjectUtils" +} \ No newline at end of file diff --git a/Java/commons-lang-ObjectUtils_724/Dockerfile b/Java/commons-lang-ObjectUtils_724/Dockerfile new file mode 100644 index 000000000..7b7fbe349 --- /dev/null +++ b/Java/commons-lang-ObjectUtils_724/Dockerfile @@ -0,0 +1,18 @@ +FROM ghcr.io/kupl/starlab-benchmarks/java-base:commons-lang + +ENV TZ=Asia/Seoul + +COPY ./metadata.json . +COPY ./npe.json . +COPY ./buggy.java /tmp/buggy.java +RUN export BUGGY_PATH=$(cat metadata.json | jq -r ".npe.filepath") \ + && export BUGGY_LINE=$(cat metadata.json | jq -r ".npe.line") \ + && export BUGGY_MTHD=$(cat metadata.json | jq -r ".npe.npe_method") \ + && mv /tmp/buggy.java $BUGGY_PATH \ + && echo "[{\"filepath\": \"$BUGGY_PATH\", \"line\": $BUGGY_LINE, \"method_name\": \"$BUGGY_MTHD\"}]" | jq . > traces.json + +RUN git init . && git add -A + +RUN $(cat metadata.json | jq -r ".buildCommand") + +RUN $(cat metadata.json | jq -r ".testCommand"); if [ $? -eq 0 ]; then exit 1; fi diff --git a/Java/commons-lang-ObjectUtils_724/buggy.java b/Java/commons-lang-ObjectUtils_724/buggy.java new file mode 100644 index 000000000..7ed91793b --- /dev/null +++ b/Java/commons-lang-ObjectUtils_724/buggy.java @@ -0,0 +1,1036 @@ +/* + * 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.Serializable; +import java.lang.reflect.Array; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.Map; +import java.util.TreeSet; + +import org.apache.commons.lang3.exception.CloneFailedException; +import org.apache.commons.lang3.mutable.MutableInt; +import org.apache.commons.lang3.text.StrBuilder; + +/** + *

Operations on {@code Object}.

+ * + *

This class tries to handle {@code null} input gracefully. + * An exception will generally not be thrown for a {@code null} input. + * Each method documents its behaviour in more detail.

+ * + *

#ThreadSafe#

+ * @since 1.0 + */ +//@Immutable +public class ObjectUtils { + + /** + *

Singleton used as a {@code null} placeholder where + * {@code null} has another meaning.

+ * + *

For example, in a {@code HashMap} the + * {@link java.util.HashMap#get(java.lang.Object)} method returns + * {@code null} if the {@code Map} contains {@code null} or if there + * is no matching key. The {@code Null} placeholder can be used to + * distinguish between these two cases.

+ * + *

Another example is {@code Hashtable}, where {@code null} + * cannot be stored.

+ * + *

This instance is Serializable.

+ */ + public static final Null NULL = new Null(); + + /** + *

{@code ObjectUtils} instances should NOT be constructed in + * standard programming. Instead, the static methods on the class should + * be used, such as {@code ObjectUtils.defaultIfNull("a","b");}.

+ * + *

This constructor is public to permit tools that require a JavaBean + * instance to operate.

+ */ + public ObjectUtils() { + super(); + } + + // Defaulting + //----------------------------------------------------------------------- + /** + *

Returns a default value if the object passed is {@code null}.

+ * + *
+     * ObjectUtils.defaultIfNull(null, null)      = null
+     * ObjectUtils.defaultIfNull(null, "")        = ""
+     * ObjectUtils.defaultIfNull(null, "zz")      = "zz"
+     * ObjectUtils.defaultIfNull("abc", *)        = "abc"
+     * ObjectUtils.defaultIfNull(Boolean.TRUE, *) = Boolean.TRUE
+     * 
+ * + * @param the type of the object + * @param object the {@code Object} to test, may be {@code null} + * @param defaultValue the default value to return, may be {@code null} + * @return {@code object} if it is not {@code null}, defaultValue otherwise + */ + public static T defaultIfNull(final T object, final T defaultValue) { + return object != null ? object : defaultValue; + } + + /** + *

Returns the first value in the array which is not {@code null}. + * If all the values are {@code null} or the array is {@code null} + * or empty then {@code null} is returned.

+ * + *
+     * ObjectUtils.firstNonNull(null, null)      = null
+     * ObjectUtils.firstNonNull(null, "")        = ""
+     * ObjectUtils.firstNonNull(null, null, "")  = ""
+     * ObjectUtils.firstNonNull(null, "zz")      = "zz"
+     * ObjectUtils.firstNonNull("abc", *)        = "abc"
+     * ObjectUtils.firstNonNull(null, "xyz", *)  = "xyz"
+     * ObjectUtils.firstNonNull(Boolean.TRUE, *) = Boolean.TRUE
+     * ObjectUtils.firstNonNull()                = null
+     * 
+ * + * @param the component type of the array + * @param values the values to test, may be {@code null} or empty + * @return the first value from {@code values} which is not {@code null}, + * or {@code null} if there are no non-null values + * @since 3.0 + */ + public static T firstNonNull(final T... values) { + if (values != null) { + for (final T val : values) { + if (val != null) { + return val; + } + } + } + return null; + } + + /** + * Checks if any value in the given array is not {@code null}. + * + *

+ * If all the values are {@code null} or the array is {@code null} + * or empty then {@code false} is returned. Otherwise {@code true} is returned. + *

+ * + *
+     * ObjectUtils.anyNotNull(*)                = true
+     * ObjectUtils.anyNotNull(*, null)          = true
+     * ObjectUtils.anyNotNull(null, *)          = true
+     * ObjectUtils.anyNotNull(null, null, *, *) = true
+     * ObjectUtils.anyNotNull(null)             = false
+     * ObjectUtils.anyNotNull(null, null)       = false
+     * 
+ * + * @param values the values to test, may be {@code null} or empty + * @return {@code true} if there is at least one non-null value in the array, + * {@code false} if all values in the array are {@code null}s. + * If the array is {@code null} or empty {@code false} is also returned. + * @since 3.5 + */ + public static boolean anyNotNull(final Object... values) { + return firstNonNull(values) != null; + } + + /** + * Checks if all values in the array are not {@code nulls}. + * + *

+ * If any value is {@code null} or the array is {@code null} then + * {@code false} is returned. If all elements in array are not + * {@code null} or the array is empty (contains no elements) {@code true} + * is returned. + *

+ * + *
+     * ObjectUtils.allNotNull(*)             = true
+     * ObjectUtils.allNotNull(*, *)          = true
+     * ObjectUtils.allNotNull(null)          = false
+     * ObjectUtils.allNotNull(null, null)    = false
+     * ObjectUtils.allNotNull(null, *)       = false
+     * ObjectUtils.allNotNull(*, null)       = false
+     * ObjectUtils.allNotNull(*, *, null, *) = false
+     * 
+ * + * @param values the values to test, may be {@code null} or empty + * @return {@code false} if there is at least one {@code null} value in the array or the array is {@code null}, + * {@code true} if all values in the array are not {@code null}s or array contains no elements. + * @since 3.5 + */ + public static boolean allNotNull(final Object... values) { + if (values == null) { + return false; + } + + for (final Object val : values) { + if (val == null) { + return false; + } + } + + return true; + } + + // Null-safe equals/hashCode + //----------------------------------------------------------------------- + /** + *

Compares two objects for equality, where either one or both + * objects may be {@code null}.

+ * + *
+     * ObjectUtils.equals(null, null)                  = true
+     * ObjectUtils.equals(null, "")                    = false
+     * ObjectUtils.equals("", null)                    = false
+     * ObjectUtils.equals("", "")                      = true
+     * ObjectUtils.equals(Boolean.TRUE, null)          = false
+     * ObjectUtils.equals(Boolean.TRUE, "true")        = false
+     * ObjectUtils.equals(Boolean.TRUE, Boolean.TRUE)  = true
+     * ObjectUtils.equals(Boolean.TRUE, Boolean.FALSE) = false
+     * 
+ * + * @param object1 the first object, may be {@code null} + * @param object2 the second object, may be {@code null} + * @return {@code true} if the values of both objects are the same + * @deprecated this method has been replaced by {@code java.util.Objects.equals(Object, Object)} in Java 7 and will + * be removed from future releases. + */ + @Deprecated + public static boolean equals(final Object object1, final Object object2) { + if (object1 == object2) { + return true; + } + if (object1 == null || object2 == null) { + return false; + } + return object1.equals(object2); + } + + /** + *

Compares two objects for inequality, where either one or both + * objects may be {@code null}.

+ * + *
+     * ObjectUtils.notEqual(null, null)                  = false
+     * ObjectUtils.notEqual(null, "")                    = true
+     * ObjectUtils.notEqual("", null)                    = true
+     * ObjectUtils.notEqual("", "")                      = false
+     * ObjectUtils.notEqual(Boolean.TRUE, null)          = true
+     * ObjectUtils.notEqual(Boolean.TRUE, "true")        = true
+     * ObjectUtils.notEqual(Boolean.TRUE, Boolean.TRUE)  = false
+     * ObjectUtils.notEqual(Boolean.TRUE, Boolean.FALSE) = true
+     * 
+ * + * @param object1 the first object, may be {@code null} + * @param object2 the second object, may be {@code null} + * @return {@code false} if the values of both objects are the same + */ + public static boolean notEqual(final Object object1, final Object object2) { + return ObjectUtils.equals(object1, object2) == false; + } + + /** + *

Gets the hash code of an object returning zero when the + * object is {@code null}.

+ * + *
+     * ObjectUtils.hashCode(null)   = 0
+     * ObjectUtils.hashCode(obj)    = obj.hashCode()
+     * 
+ * + * @param obj the object to obtain the hash code of, may be {@code null} + * @return the hash code of the object, or zero if null + * @since 2.1 + * @deprecated this method has been replaced by {@code java.util.Objects.hashCode(Object)} in Java 7 and will be + * removed in future releases + */ + @Deprecated + public static int hashCode(final Object obj) { + // hashCode(Object) retained for performance, as hash code is often critical + return obj == null ? 0 : obj.hashCode(); + } + + /** + *

Gets the hash code for multiple objects.

+ * + *

This allows a hash code to be rapidly calculated for a number of objects. + * The hash code for a single object is the not same as {@link #hashCode(Object)}. + * The hash code for multiple objects is the same as that calculated by an + * {@code ArrayList} containing the specified objects.

+ * + *
+     * ObjectUtils.hashCodeMulti()                 = 1
+     * ObjectUtils.hashCodeMulti((Object[]) null)  = 1
+     * ObjectUtils.hashCodeMulti(a)                = 31 + a.hashCode()
+     * ObjectUtils.hashCodeMulti(a,b)              = (31 + a.hashCode()) * 31 + b.hashCode()
+     * ObjectUtils.hashCodeMulti(a,b,c)            = ((31 + a.hashCode()) * 31 + b.hashCode()) * 31 + c.hashCode()
+     * 
+ * + * @param objects the objects to obtain the hash code of, may be {@code null} + * @return the hash code of the objects, or zero if null + * @since 3.0 + * @deprecated this method has been replaced by {@code java.util.Objects.hash(Object...)} in Java 7 and will be + * removed in future releases. + */ + @Deprecated + public static int hashCodeMulti(final Object... objects) { + int hash = 1; + if (objects != null) { + for (final Object object : objects) { + final int tmpHash = ObjectUtils.hashCode(object); + hash = hash * 31 + tmpHash; + } + } + return hash; + } + + // Identity ToString + //----------------------------------------------------------------------- + /** + *

Gets the toString that would be produced by {@code Object} + * if a class did not override toString itself. {@code null} + * will return {@code null}.

+ * + *
+     * ObjectUtils.identityToString(null)         = null
+     * ObjectUtils.identityToString("")           = "java.lang.String@1e23"
+     * ObjectUtils.identityToString(Boolean.TRUE) = "java.lang.Boolean@7fa"
+     * 
+ * + * @param object the object to create a toString for, may be + * {@code null} + * @return the default toString text, or {@code null} if + * {@code null} passed in + */ + public static String identityToString(final Object object) { + if (object == null) { + return null; + } + final StringBuilder builder = new StringBuilder(); + identityToString(builder, object); + return builder.toString(); + } + + /** + *

Appends the toString that would be produced by {@code Object} + * if a class did not override toString itself. {@code null} + * will throw a NullPointerException for either of the two parameters.

+ * + *
+     * ObjectUtils.identityToString(appendable, "")            = appendable.append("java.lang.String@1e23"
+     * ObjectUtils.identityToString(appendable, Boolean.TRUE)  = appendable.append("java.lang.Boolean@7fa"
+     * ObjectUtils.identityToString(appendable, Boolean.TRUE)  = appendable.append("java.lang.Boolean@7fa")
+     * 
+ * + * @param appendable the appendable to append to + * @param object the object to create a toString for + * @throws IOException if an I/O error occurs + * @since 3.2 + */ + public static void identityToString(final Appendable appendable, final Object object) throws IOException { + if (object == null) { + throw new NullPointerException("Cannot get the toString of a null identity"); + } + appendable.append(object.getClass().getName()) + .append('@') + .append(Integer.toHexString(System.identityHashCode(object))); + } + + /** + *

Appends the toString that would be produced by {@code Object} + * if a class did not override toString itself. {@code null} + * will throw a NullPointerException for either of the two parameters.

+ * + *
+     * ObjectUtils.identityToString(builder, "")            = builder.append("java.lang.String@1e23"
+     * ObjectUtils.identityToString(builder, Boolean.TRUE)  = builder.append("java.lang.Boolean@7fa"
+     * ObjectUtils.identityToString(builder, Boolean.TRUE)  = builder.append("java.lang.Boolean@7fa")
+     * 
+ * + * @param builder the builder to append to + * @param object the object to create a toString for + * @since 3.2 + */ + public static void identityToString(final StrBuilder builder, final Object object) { + if (object == null) { + throw new NullPointerException("Cannot get the toString of a null identity"); + } + builder.append(object.getClass().getName()) + .append('@') + .append(Integer.toHexString(System.identityHashCode(object))); + } + + /** + *

Appends the toString that would be produced by {@code Object} + * if a class did not override toString itself. {@code null} + * will throw a NullPointerException for either of the two parameters.

+ * + *
+     * ObjectUtils.identityToString(buf, "")            = buf.append("java.lang.String@1e23"
+     * ObjectUtils.identityToString(buf, Boolean.TRUE)  = buf.append("java.lang.Boolean@7fa"
+     * ObjectUtils.identityToString(buf, Boolean.TRUE)  = buf.append("java.lang.Boolean@7fa")
+     * 
+ * + * @param buffer the buffer to append to + * @param object the object to create a toString for + * @since 2.4 + */ + public static void identityToString(final StringBuffer buffer, final Object object) { + if (object == null) { + throw new NullPointerException("Cannot get the toString of a null identity"); + } + buffer.append(object.getClass().getName()) + .append('@') + .append(Integer.toHexString(System.identityHashCode(object))); + } + + /** + *

Appends the toString that would be produced by {@code Object} + * if a class did not override toString itself. {@code null} + * will throw a NullPointerException for either of the two parameters.

+ * + *
+     * ObjectUtils.identityToString(builder, "")            = builder.append("java.lang.String@1e23"
+     * ObjectUtils.identityToString(builder, Boolean.TRUE)  = builder.append("java.lang.Boolean@7fa"
+     * ObjectUtils.identityToString(builder, Boolean.TRUE)  = builder.append("java.lang.Boolean@7fa")
+     * 
+ * + * @param builder the builder to append to + * @param object the object to create a toString for + * @since 3.2 + */ + public static void identityToString(final StringBuilder builder, final Object object) { + if (object == null) { + throw new NullPointerException("Cannot get the toString of a null identity"); + } + builder.append(object.getClass().getName()) + .append('@') + .append(Integer.toHexString(System.identityHashCode(object))); + } + + // ToString + //----------------------------------------------------------------------- + /** + *

Gets the {@code toString} of an {@code Object} returning + * an empty string ("") if {@code null} input.

+ * + *
+     * ObjectUtils.toString(null)         = ""
+     * ObjectUtils.toString("")           = ""
+     * ObjectUtils.toString("bat")        = "bat"
+     * ObjectUtils.toString(Boolean.TRUE) = "true"
+     * 
+ * + * @see StringUtils#defaultString(String) + * @see String#valueOf(Object) + * @param obj the Object to {@code toString}, may be null + * @return the passed in Object's toString, or {@code ""} if {@code null} input + * @since 2.0 + * @deprecated this method has been replaced by {@code java.util.Objects.toString(Object)} in Java 7 and will be + * removed in future releases. Note however that said method will return "null" for null references, while this + * method returns and empty String. To preserve behavior use {@code java.util.Objects.toString(myObject, "")} + */ + @Deprecated + public static String toString(final Object obj) { + return obj == null ? StringUtils.EMPTY : obj.toString(); + } + + /** + *

Gets the {@code toString} of an {@code Object} returning + * a specified text if {@code null} input.

+ * + *
+     * ObjectUtils.toString(null, null)           = null
+     * ObjectUtils.toString(null, "null")         = "null"
+     * ObjectUtils.toString("", "null")           = ""
+     * ObjectUtils.toString("bat", "null")        = "bat"
+     * ObjectUtils.toString(Boolean.TRUE, "null") = "true"
+     * 
+ * + * @see StringUtils#defaultString(String,String) + * @see String#valueOf(Object) + * @param obj the Object to {@code toString}, may be null + * @param nullStr the String to return if {@code null} input, may be null + * @return the passed in Object's toString, or {@code nullStr} if {@code null} input + * @since 2.0 + * @deprecated this method has been replaced by {@code java.util.Objects.toString(Object, String)} in Java 7 and + * will be removed in future releases. + */ + @Deprecated + public static String toString(final Object obj, final String nullStr) { + return obj == null ? nullStr : obj.toString(); + } + + // Comparable + //----------------------------------------------------------------------- + /** + *

Null safe comparison of Comparables.

+ * + * @param type of the values processed by this method + * @param values the set of comparable values, may be null + * @return + *
    + *
  • If any objects are non-null and unequal, the lesser object. + *
  • If all objects are non-null and equal, the first. + *
  • If any of the comparables are null, the lesser of the non-null objects. + *
  • If all the comparables are null, null is returned. + *
+ */ + public static > T min(final T... values) { + T result = null; + if (values != null) { + for (final T value : values) { + if (compare(value, result, true) < 0) { + result = value; + } + } + } + return result; + } + + /** + *

Null safe comparison of Comparables.

+ * + * @param type of the values processed by this method + * @param values the set of comparable values, may be null + * @return + *
    + *
  • If any objects are non-null and unequal, the greater object. + *
  • If all objects are non-null and equal, the first. + *
  • If any of the comparables are null, the greater of the non-null objects. + *
  • If all the comparables are null, null is returned. + *
+ */ + public static > T max(final T... values) { + T result = null; + if (values != null) { + for (final T value : values) { + if (compare(value, result, false) > 0) { + result = value; + } + } + } + return result; + } + + /** + *

Null safe comparison of Comparables. + * {@code null} is assumed to be less than a non-{@code null} value.

+ * + * @param type of the values processed by this method + * @param c1 the first comparable, may be null + * @param c2 the second comparable, may be null + * @return a negative value if c1 < c2, zero if c1 = c2 + * and a positive value if c1 > c2 + */ + public static > int compare(final T c1, final T c2) { + return compare(c1, c2, false); + } + + /** + *

Null safe comparison of Comparables.

+ * + * @param type of the values processed by this method + * @param c1 the first comparable, may be null + * @param c2 the second comparable, may be null + * @param nullGreater if true {@code null} is considered greater + * than a non-{@code null} value or if false {@code null} is + * considered less than a Non-{@code null} value + * @return a negative value if c1 < c2, zero if c1 = c2 + * and a positive value if c1 > c2 + * @see java.util.Comparator#compare(Object, Object) + */ + public static > int compare(final T c1, final T c2, final boolean nullGreater) { + if (c1 == c2) { + return 0; + } else if (c1 == null) { + return nullGreater ? 1 : -1; + } else if (c2 == null) { + return nullGreater ? -1 : 1; + } + return c1.compareTo(c2); + } + + /** + * Find the "best guess" middle value among comparables. If there is an even + * number of total values, the lower of the two middle values will be returned. + * @param type of values processed by this method + * @param items to compare + * @return T at middle position + * @throws NullPointerException if items is {@code null} + * @throws IllegalArgumentException if items is empty or contains {@code null} values + * @since 3.0.1 + */ + public static > T median(final T... items) { + Validate.notEmpty(items); + Validate.noNullElements(items); + final TreeSet sort = new TreeSet(); + Collections.addAll(sort, items); + @SuppressWarnings("unchecked") //we know all items added were T instances + final + T result = (T) sort.toArray()[(sort.size() - 1) / 2]; + return result; + } + + /** + * Find the "best guess" middle value among comparables. If there is an even + * number of total values, the lower of the two middle values will be returned. + * @param type of values processed by this method + * @param comparator to use for comparisons + * @param items to compare + * @return T at middle position + * @throws NullPointerException if items or comparator is {@code null} + * @throws IllegalArgumentException if items is empty or contains {@code null} values + * @since 3.0.1 + */ + public static T median(final Comparator comparator, final T... items) { + Validate.notEmpty(items, "null/empty items"); + Validate.noNullElements(items); + Validate.notNull(comparator, "null comparator"); + final TreeSet sort = new TreeSet(comparator); + Collections.addAll(sort, items); + @SuppressWarnings("unchecked") //we know all items added were T instances + final + T result = (T) sort.toArray()[(sort.size() - 1) / 2]; + return result; + } + + // Mode + //----------------------------------------------------------------------- + /** + * Find the most frequently occurring item. + * + * @param type of values processed by this method + * @param items to check + * @return most populous T, {@code null} if non-unique or no items supplied + * @since 3.0.1 + */ + public static T mode(final T... items) { + if (ArrayUtils.isNotEmpty(items)) { + final HashMap occurrences = new HashMap(items.length); + for (final T t : items) { + final MutableInt count = occurrences.get(t); + if (count == null) { + occurrences.put(t, new MutableInt(1)); + } else { + count.increment(); + } + } + T result = null; + int max = 0; + for (final Map.Entry e : occurrences.entrySet()) { + final int cmp = e.getValue().intValue(); + if (cmp == max) { + result = null; + } else if (cmp > max) { + max = cmp; + result = e.getKey(); + } + } + return result; + } + return null; + } + + // cloning + //----------------------------------------------------------------------- + /** + *

Clone an object.

+ * + * @param the type of the object + * @param obj the object to clone, null returns null + * @return the clone if the object implements {@link Cloneable} otherwise {@code null} + * @throws CloneFailedException if the object is cloneable and the clone operation fails + * @since 3.0 + */ + public static T clone(final T obj) { + if (obj instanceof Cloneable) { + final Object result; + if (obj.getClass().isArray()) { + final Class componentType = obj.getClass().getComponentType(); + if (!componentType.isPrimitive()) { + result = ((Object[]) obj).clone(); + } else { + int length = Array.getLength(obj); + result = Array.newInstance(componentType, length); + while (length-- > 0) { + Array.set(result, length, Array.get(obj, length)); + } + } + } else { + try { + final Method clone = obj.getClass().getMethod("clone"); + result = clone.invoke(obj); + } catch (final NoSuchMethodException e) { + throw new CloneFailedException("Cloneable type " + + obj.getClass().getName() + + " has no clone method", e); + } catch (final IllegalAccessException e) { + throw new CloneFailedException("Cannot clone Cloneable type " + + obj.getClass().getName(), e); + } catch (final InvocationTargetException e) { + throw new CloneFailedException("Exception cloning Cloneable type " + + obj.getClass().getName(), e.getCause()); + } + } + @SuppressWarnings("unchecked") // OK because input is of type T + final T checked = (T) result; + return checked; + } + + return null; + } + + /** + *

Clone an object if possible.

+ * + *

This method is similar to {@link #clone(Object)}, but will return the provided + * instance as the return value instead of {@code null} if the instance + * is not cloneable. This is more convenient if the caller uses different + * implementations (e.g. of a service) and some of the implementations do not allow concurrent + * processing or have state. In such cases the implementation can simply provide a proper + * clone implementation and the caller's code does not have to change.

+ * + * @param the type of the object + * @param obj the object to clone, null returns null + * @return the clone if the object implements {@link Cloneable} otherwise the object itself + * @throws CloneFailedException if the object is cloneable and the clone operation fails + * @since 3.0 + */ +/** + *

Clone an object if possible.

+ * + *

This method is similar to {@link #clone(Object)}, but will return the provided + * instance as the return value instead of {@code null} if the instance + * is not cloneable. This is more convenient if the caller uses different + * implementations (e.g. of a service) and some of the implementations do not allow concurrent + * processing or have state. In such cases the implementation can simply provide a proper + * clone implementation and the caller's code does not have to change.

+ * + * @param + * the type of the object + * @param obj + * the object to clone, null returns null + * @return the clone if the object implements {@link Cloneable} otherwise the object itself + * @throws CloneFailedException + * if the object is cloneable and the clone operation fails + * @since 3.0 + */ +public static T cloneIfPossible(final T obj) { + final T clone = org.apache.commons.lang3.ObjectUtils.clone(obj); + return /* NPEX_NULL_EXP */ + clone; +} + + // Null + //----------------------------------------------------------------------- + /** + *

Class used as a null placeholder where {@code null} + * has another meaning.

+ * + *

For example, in a {@code HashMap} the + * {@link java.util.HashMap#get(java.lang.Object)} method returns + * {@code null} if the {@code Map} contains {@code null} or if there is + * no matching key. The {@code Null} placeholder can be used to distinguish + * between these two cases.

+ * + *

Another example is {@code Hashtable}, where {@code null} + * cannot be stored.

+ */ + public static class Null implements Serializable { + /** + * Required for serialization support. Declare serialization compatibility with Commons Lang 1.0 + * + * @see java.io.Serializable + */ + private static final long serialVersionUID = 7092611880189329093L; + + /** + * Restricted constructor - singleton. + */ + Null() { + super(); + } + + /** + *

Ensure singleton.

+ * + * @return the singleton value + */ + private Object readResolve() { + return ObjectUtils.NULL; + } + } + + + // Constants (LANG-816): + /* + These methods ensure constants are not inlined by javac. + For example, typically a developer might declare a constant like so: + + public final static int MAGIC_NUMBER = 5; + + Should a different jar file refer to this, and the MAGIC_NUMBER + is changed a later date (e.g., MAGIC_NUMBER = 6), the different jar + file will need to recompile itself. This is because javac + typically inlines the primitive or String constant directly into + the bytecode, and removes the reference to the MAGIC_NUMBER field. + + To help the other jar (so that it does not need to recompile + when constants are changed) the original developer can declare + their constant using one of the CONST() utility methods, instead: + + public final static int MAGIC_NUMBER = CONST(5); + */ + + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static boolean MAGIC_FLAG = ObjectUtils.CONST(true);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the boolean value to return + * @return the boolean v, unchanged + * @since 3.2 + */ + public static boolean CONST(final boolean v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static byte MAGIC_BYTE = ObjectUtils.CONST((byte) 127);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the byte value to return + * @return the byte v, unchanged + * @since 3.2 + */ + public static byte CONST(final byte v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static byte MAGIC_BYTE = ObjectUtils.CONST_BYTE(127);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the byte literal (as an int) value to return + * @throws IllegalArgumentException if the value passed to v + * is larger than a byte, that is, smaller than -128 or + * larger than 127. + * @return the byte v, unchanged + * @since 3.2 + */ + public static byte CONST_BYTE(final int v) throws IllegalArgumentException { + if (v < Byte.MIN_VALUE || v > Byte.MAX_VALUE) { + throw new IllegalArgumentException("Supplied value must be a valid byte literal between -128 and 127: [" + v + "]"); + } + return (byte) v; + } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static char MAGIC_CHAR = ObjectUtils.CONST('a');
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the char value to return + * @return the char v, unchanged + * @since 3.2 + */ + public static char CONST(final char v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static short MAGIC_SHORT = ObjectUtils.CONST((short) 123);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the short value to return + * @return the short v, unchanged + * @since 3.2 + */ + public static short CONST(final short v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static short MAGIC_SHORT = ObjectUtils.CONST_SHORT(127);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the short literal (as an int) value to return + * @throws IllegalArgumentException if the value passed to v + * is larger than a short, that is, smaller than -32768 or + * larger than 32767. + * @return the byte v, unchanged + * @since 3.2 + */ + public static short CONST_SHORT(final int v) throws IllegalArgumentException { + if (v < Short.MIN_VALUE || v > Short.MAX_VALUE) { + throw new IllegalArgumentException("Supplied value must be a valid byte literal between -32768 and 32767: [" + v + "]"); + } + return (short) v; + } + + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static int MAGIC_INT = ObjectUtils.CONST(123);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the int value to return + * @return the int v, unchanged + * @since 3.2 + */ + public static int CONST(final int v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static long MAGIC_LONG = ObjectUtils.CONST(123L);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the long value to return + * @return the long v, unchanged + * @since 3.2 + */ + public static long CONST(final long v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static float MAGIC_FLOAT = ObjectUtils.CONST(1.0f);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the float value to return + * @return the float v, unchanged + * @since 3.2 + */ + public static float CONST(final float v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static double MAGIC_DOUBLE = ObjectUtils.CONST(1.0);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the double value to return + * @return the double v, unchanged + * @since 3.2 + */ + public static double CONST(final double v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static String MAGIC_STRING = ObjectUtils.CONST("abc");
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param the Object type + * @param v the genericized Object value to return (typically a String). + * @return the genericized Object v, unchanged (typically a String). + * @since 3.2 + */ + public static T CONST(final T v) { return v; } + +} diff --git a/Java/commons-lang-ObjectUtils_724/metadata.json b/Java/commons-lang-ObjectUtils_724/metadata.json new file mode 100644 index 000000000..ecf91f61b --- /dev/null +++ b/Java/commons-lang-ObjectUtils_724/metadata.json @@ -0,0 +1,21 @@ +{ + "language": "java", + "id": "commons-lang-ObjectUtils_724", + "buggyPath": ".", + "referencePath": null, + "buildCommand": "mvn package -V -B -Denforcer.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true -Drat.skip=true -Dlicense.skip=true -Dfindbugs.skip=true -Dgpg.skip=true -Dskip.npm=true -Dskip.gulp=true -Dskip.bower=true -Drat.numUnapprovedLicenses=100 -DskipTests=true -DskipITs=true -Dtest=None -DfailIfNoTests=false", + "testCommand": "mvn test -V -B -Denforcer.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true -Drat.skip=true -Dlicense.skip=true -Dfindbugs.skip=true -Dgpg.skip=true -Dskip.npm=true -Dskip.gulp=true -Dskip.bower=true -Drat.numUnapprovedLicenses=100", + "categories": [ + "safety", + "npe" + ], + "npe": { + "filepath": "src/main/java/org/apache/commons/lang3/ObjectUtils.java", + "line": 744, + "npe_method": "cloneIfPossible", + "deref_field": "clone", + "npe_class": "ObjectUtils", + "repo": "commons-lang", + "bug_id": "ObjectUtils_724" + } +} diff --git a/Java/commons-lang-ObjectUtils_724/npe.json b/Java/commons-lang-ObjectUtils_724/npe.json new file mode 100644 index 000000000..30405a37a --- /dev/null +++ b/Java/commons-lang-ObjectUtils_724/npe.json @@ -0,0 +1,7 @@ +{ + "filepath": "src/main/java/org/apache/commons/lang3/ObjectUtils.java", + "line": 744, + "npe_method": "cloneIfPossible", + "deref_field": "clone", + "npe_class": "ObjectUtils" +} \ No newline at end of file diff --git a/Java/commons-lang-ObjectUtils_95/Dockerfile b/Java/commons-lang-ObjectUtils_95/Dockerfile new file mode 100644 index 000000000..7b7fbe349 --- /dev/null +++ b/Java/commons-lang-ObjectUtils_95/Dockerfile @@ -0,0 +1,18 @@ +FROM ghcr.io/kupl/starlab-benchmarks/java-base:commons-lang + +ENV TZ=Asia/Seoul + +COPY ./metadata.json . +COPY ./npe.json . +COPY ./buggy.java /tmp/buggy.java +RUN export BUGGY_PATH=$(cat metadata.json | jq -r ".npe.filepath") \ + && export BUGGY_LINE=$(cat metadata.json | jq -r ".npe.line") \ + && export BUGGY_MTHD=$(cat metadata.json | jq -r ".npe.npe_method") \ + && mv /tmp/buggy.java $BUGGY_PATH \ + && echo "[{\"filepath\": \"$BUGGY_PATH\", \"line\": $BUGGY_LINE, \"method_name\": \"$BUGGY_MTHD\"}]" | jq . > traces.json + +RUN git init . && git add -A + +RUN $(cat metadata.json | jq -r ".buildCommand") + +RUN $(cat metadata.json | jq -r ".testCommand"); if [ $? -eq 0 ]; then exit 1; fi diff --git a/Java/commons-lang-ObjectUtils_95/buggy.java b/Java/commons-lang-ObjectUtils_95/buggy.java new file mode 100644 index 000000000..76049bf2b --- /dev/null +++ b/Java/commons-lang-ObjectUtils_95/buggy.java @@ -0,0 +1,1038 @@ +/* + * 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.Serializable; +import java.lang.reflect.Array; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.Map; +import java.util.TreeSet; + +import org.apache.commons.lang3.exception.CloneFailedException; +import org.apache.commons.lang3.mutable.MutableInt; +import org.apache.commons.lang3.text.StrBuilder; + +/** + *

Operations on {@code Object}.

+ * + *

This class tries to handle {@code null} input gracefully. + * An exception will generally not be thrown for a {@code null} input. + * Each method documents its behaviour in more detail.

+ * + *

#ThreadSafe#

+ * @since 1.0 + */ +//@Immutable +public class ObjectUtils { + + /** + *

Singleton used as a {@code null} placeholder where + * {@code null} has another meaning.

+ * + *

For example, in a {@code HashMap} the + * {@link java.util.HashMap#get(java.lang.Object)} method returns + * {@code null} if the {@code Map} contains {@code null} or if there + * is no matching key. The {@code Null} placeholder can be used to + * distinguish between these two cases.

+ * + *

Another example is {@code Hashtable}, where {@code null} + * cannot be stored.

+ * + *

This instance is Serializable.

+ */ + public static final Null NULL = new Null(); + + /** + *

{@code ObjectUtils} instances should NOT be constructed in + * standard programming. Instead, the static methods on the class should + * be used, such as {@code ObjectUtils.defaultIfNull("a","b");}.

+ * + *

This constructor is public to permit tools that require a JavaBean + * instance to operate.

+ */ + public ObjectUtils() { + super(); + } + + // Defaulting + //----------------------------------------------------------------------- + /** + *

Returns a default value if the object passed is {@code null}.

+ * + *
+     * ObjectUtils.defaultIfNull(null, null)      = null
+     * ObjectUtils.defaultIfNull(null, "")        = ""
+     * ObjectUtils.defaultIfNull(null, "zz")      = "zz"
+     * ObjectUtils.defaultIfNull("abc", *)        = "abc"
+     * ObjectUtils.defaultIfNull(Boolean.TRUE, *) = Boolean.TRUE
+     * 
+ * + * @param the type of the object + * @param object the {@code Object} to test, may be {@code null} + * @param defaultValue the default value to return, may be {@code null} + * @return {@code object} if it is not {@code null}, defaultValue otherwise + */ +// Defaulting +// ----------------------------------------------------------------------- +/** + *

Returns a default value if the object passed is {@code null}.

+ * + *
+ * ObjectUtils.defaultIfNull(null, null)      = null
+ * ObjectUtils.defaultIfNull(null, "")        = ""
+ * ObjectUtils.defaultIfNull(null, "zz")      = "zz"
+ * ObjectUtils.defaultIfNull("abc", *)        = "abc"
+ * ObjectUtils.defaultIfNull(Boolean.TRUE, *) = Boolean.TRUE
+ * 
+ * + * @param + * the type of the object + * @param object + * the {@code Object} to test, may be {@code null} + * @param defaultValue + * the default value to return, may be {@code null} + * @return {@code object} if it is not {@code null}, defaultValue otherwise + */ +public static T defaultIfNull(final T object, final T defaultValue) { + return /* NPEX_NULL_EXP */ + object; +} + + /** + *

Returns the first value in the array which is not {@code null}. + * If all the values are {@code null} or the array is {@code null} + * or empty then {@code null} is returned.

+ * + *
+     * ObjectUtils.firstNonNull(null, null)      = null
+     * ObjectUtils.firstNonNull(null, "")        = ""
+     * ObjectUtils.firstNonNull(null, null, "")  = ""
+     * ObjectUtils.firstNonNull(null, "zz")      = "zz"
+     * ObjectUtils.firstNonNull("abc", *)        = "abc"
+     * ObjectUtils.firstNonNull(null, "xyz", *)  = "xyz"
+     * ObjectUtils.firstNonNull(Boolean.TRUE, *) = Boolean.TRUE
+     * ObjectUtils.firstNonNull()                = null
+     * 
+ * + * @param the component type of the array + * @param values the values to test, may be {@code null} or empty + * @return the first value from {@code values} which is not {@code null}, + * or {@code null} if there are no non-null values + * @since 3.0 + */ + public static T firstNonNull(final T... values) { + if (values != null) { + for (final T val : values) { + if (val != null) { + return val; + } + } + } + return null; + } + + /** + * Checks if any value in the given array is not {@code null}. + * + *

+ * If all the values are {@code null} or the array is {@code null} + * or empty then {@code false} is returned. Otherwise {@code true} is returned. + *

+ * + *
+     * ObjectUtils.anyNotNull(*)                = true
+     * ObjectUtils.anyNotNull(*, null)          = true
+     * ObjectUtils.anyNotNull(null, *)          = true
+     * ObjectUtils.anyNotNull(null, null, *, *) = true
+     * ObjectUtils.anyNotNull(null)             = false
+     * ObjectUtils.anyNotNull(null, null)       = false
+     * 
+ * + * @param values the values to test, may be {@code null} or empty + * @return {@code true} if there is at least one non-null value in the array, + * {@code false} if all values in the array are {@code null}s. + * If the array is {@code null} or empty {@code false} is also returned. + * @since 3.5 + */ + public static boolean anyNotNull(final Object... values) { + return firstNonNull(values) != null; + } + + /** + * Checks if all values in the array are not {@code nulls}. + * + *

+ * If any value is {@code null} or the array is {@code null} then + * {@code false} is returned. If all elements in array are not + * {@code null} or the array is empty (contains no elements) {@code true} + * is returned. + *

+ * + *
+     * ObjectUtils.allNotNull(*)             = true
+     * ObjectUtils.allNotNull(*, *)          = true
+     * ObjectUtils.allNotNull(null)          = false
+     * ObjectUtils.allNotNull(null, null)    = false
+     * ObjectUtils.allNotNull(null, *)       = false
+     * ObjectUtils.allNotNull(*, null)       = false
+     * ObjectUtils.allNotNull(*, *, null, *) = false
+     * 
+ * + * @param values the values to test, may be {@code null} or empty + * @return {@code false} if there is at least one {@code null} value in the array or the array is {@code null}, + * {@code true} if all values in the array are not {@code null}s or array contains no elements. + * @since 3.5 + */ + public static boolean allNotNull(final Object... values) { + if (values == null) { + return false; + } + + for (final Object val : values) { + if (val == null) { + return false; + } + } + + return true; + } + + // Null-safe equals/hashCode + //----------------------------------------------------------------------- + /** + *

Compares two objects for equality, where either one or both + * objects may be {@code null}.

+ * + *
+     * ObjectUtils.equals(null, null)                  = true
+     * ObjectUtils.equals(null, "")                    = false
+     * ObjectUtils.equals("", null)                    = false
+     * ObjectUtils.equals("", "")                      = true
+     * ObjectUtils.equals(Boolean.TRUE, null)          = false
+     * ObjectUtils.equals(Boolean.TRUE, "true")        = false
+     * ObjectUtils.equals(Boolean.TRUE, Boolean.TRUE)  = true
+     * ObjectUtils.equals(Boolean.TRUE, Boolean.FALSE) = false
+     * 
+ * + * @param object1 the first object, may be {@code null} + * @param object2 the second object, may be {@code null} + * @return {@code true} if the values of both objects are the same + * @deprecated this method has been replaced by {@code java.util.Objects.equals(Object, Object)} in Java 7 and will + * be removed from future releases. + */ + @Deprecated + public static boolean equals(final Object object1, final Object object2) { + if (object1 == object2) { + return true; + } + if (object1 == null || object2 == null) { + return false; + } + return object1.equals(object2); + } + + /** + *

Compares two objects for inequality, where either one or both + * objects may be {@code null}.

+ * + *
+     * ObjectUtils.notEqual(null, null)                  = false
+     * ObjectUtils.notEqual(null, "")                    = true
+     * ObjectUtils.notEqual("", null)                    = true
+     * ObjectUtils.notEqual("", "")                      = false
+     * ObjectUtils.notEqual(Boolean.TRUE, null)          = true
+     * ObjectUtils.notEqual(Boolean.TRUE, "true")        = true
+     * ObjectUtils.notEqual(Boolean.TRUE, Boolean.TRUE)  = false
+     * ObjectUtils.notEqual(Boolean.TRUE, Boolean.FALSE) = true
+     * 
+ * + * @param object1 the first object, may be {@code null} + * @param object2 the second object, may be {@code null} + * @return {@code false} if the values of both objects are the same + */ + public static boolean notEqual(final Object object1, final Object object2) { + return ObjectUtils.equals(object1, object2) == false; + } + + /** + *

Gets the hash code of an object returning zero when the + * object is {@code null}.

+ * + *
+     * ObjectUtils.hashCode(null)   = 0
+     * ObjectUtils.hashCode(obj)    = obj.hashCode()
+     * 
+ * + * @param obj the object to obtain the hash code of, may be {@code null} + * @return the hash code of the object, or zero if null + * @since 2.1 + * @deprecated this method has been replaced by {@code java.util.Objects.hashCode(Object)} in Java 7 and will be + * removed in future releases + */ + @Deprecated + public static int hashCode(final Object obj) { + // hashCode(Object) retained for performance, as hash code is often critical + return obj == null ? 0 : obj.hashCode(); + } + + /** + *

Gets the hash code for multiple objects.

+ * + *

This allows a hash code to be rapidly calculated for a number of objects. + * The hash code for a single object is the not same as {@link #hashCode(Object)}. + * The hash code for multiple objects is the same as that calculated by an + * {@code ArrayList} containing the specified objects.

+ * + *
+     * ObjectUtils.hashCodeMulti()                 = 1
+     * ObjectUtils.hashCodeMulti((Object[]) null)  = 1
+     * ObjectUtils.hashCodeMulti(a)                = 31 + a.hashCode()
+     * ObjectUtils.hashCodeMulti(a,b)              = (31 + a.hashCode()) * 31 + b.hashCode()
+     * ObjectUtils.hashCodeMulti(a,b,c)            = ((31 + a.hashCode()) * 31 + b.hashCode()) * 31 + c.hashCode()
+     * 
+ * + * @param objects the objects to obtain the hash code of, may be {@code null} + * @return the hash code of the objects, or zero if null + * @since 3.0 + * @deprecated this method has been replaced by {@code java.util.Objects.hash(Object...)} in Java 7 and will be + * removed in future releases. + */ + @Deprecated + public static int hashCodeMulti(final Object... objects) { + int hash = 1; + if (objects != null) { + for (final Object object : objects) { + final int tmpHash = ObjectUtils.hashCode(object); + hash = hash * 31 + tmpHash; + } + } + return hash; + } + + // Identity ToString + //----------------------------------------------------------------------- + /** + *

Gets the toString that would be produced by {@code Object} + * if a class did not override toString itself. {@code null} + * will return {@code null}.

+ * + *
+     * ObjectUtils.identityToString(null)         = null
+     * ObjectUtils.identityToString("")           = "java.lang.String@1e23"
+     * ObjectUtils.identityToString(Boolean.TRUE) = "java.lang.Boolean@7fa"
+     * 
+ * + * @param object the object to create a toString for, may be + * {@code null} + * @return the default toString text, or {@code null} if + * {@code null} passed in + */ + public static String identityToString(final Object object) { + if (object == null) { + return null; + } + final StringBuilder builder = new StringBuilder(); + identityToString(builder, object); + return builder.toString(); + } + + /** + *

Appends the toString that would be produced by {@code Object} + * if a class did not override toString itself. {@code null} + * will throw a NullPointerException for either of the two parameters.

+ * + *
+     * ObjectUtils.identityToString(appendable, "")            = appendable.append("java.lang.String@1e23"
+     * ObjectUtils.identityToString(appendable, Boolean.TRUE)  = appendable.append("java.lang.Boolean@7fa"
+     * ObjectUtils.identityToString(appendable, Boolean.TRUE)  = appendable.append("java.lang.Boolean@7fa")
+     * 
+ * + * @param appendable the appendable to append to + * @param object the object to create a toString for + * @throws IOException if an I/O error occurs + * @since 3.2 + */ + public static void identityToString(final Appendable appendable, final Object object) throws IOException { + if (object == null) { + throw new NullPointerException("Cannot get the toString of a null identity"); + } + appendable.append(object.getClass().getName()) + .append('@') + .append(Integer.toHexString(System.identityHashCode(object))); + } + + /** + *

Appends the toString that would be produced by {@code Object} + * if a class did not override toString itself. {@code null} + * will throw a NullPointerException for either of the two parameters.

+ * + *
+     * ObjectUtils.identityToString(builder, "")            = builder.append("java.lang.String@1e23"
+     * ObjectUtils.identityToString(builder, Boolean.TRUE)  = builder.append("java.lang.Boolean@7fa"
+     * ObjectUtils.identityToString(builder, Boolean.TRUE)  = builder.append("java.lang.Boolean@7fa")
+     * 
+ * + * @param builder the builder to append to + * @param object the object to create a toString for + * @since 3.2 + */ + public static void identityToString(final StrBuilder builder, final Object object) { + if (object == null) { + throw new NullPointerException("Cannot get the toString of a null identity"); + } + builder.append(object.getClass().getName()) + .append('@') + .append(Integer.toHexString(System.identityHashCode(object))); + } + + /** + *

Appends the toString that would be produced by {@code Object} + * if a class did not override toString itself. {@code null} + * will throw a NullPointerException for either of the two parameters.

+ * + *
+     * ObjectUtils.identityToString(buf, "")            = buf.append("java.lang.String@1e23"
+     * ObjectUtils.identityToString(buf, Boolean.TRUE)  = buf.append("java.lang.Boolean@7fa"
+     * ObjectUtils.identityToString(buf, Boolean.TRUE)  = buf.append("java.lang.Boolean@7fa")
+     * 
+ * + * @param buffer the buffer to append to + * @param object the object to create a toString for + * @since 2.4 + */ + public static void identityToString(final StringBuffer buffer, final Object object) { + if (object == null) { + throw new NullPointerException("Cannot get the toString of a null identity"); + } + buffer.append(object.getClass().getName()) + .append('@') + .append(Integer.toHexString(System.identityHashCode(object))); + } + + /** + *

Appends the toString that would be produced by {@code Object} + * if a class did not override toString itself. {@code null} + * will throw a NullPointerException for either of the two parameters.

+ * + *
+     * ObjectUtils.identityToString(builder, "")            = builder.append("java.lang.String@1e23"
+     * ObjectUtils.identityToString(builder, Boolean.TRUE)  = builder.append("java.lang.Boolean@7fa"
+     * ObjectUtils.identityToString(builder, Boolean.TRUE)  = builder.append("java.lang.Boolean@7fa")
+     * 
+ * + * @param builder the builder to append to + * @param object the object to create a toString for + * @since 3.2 + */ + public static void identityToString(final StringBuilder builder, final Object object) { + if (object == null) { + throw new NullPointerException("Cannot get the toString of a null identity"); + } + builder.append(object.getClass().getName()) + .append('@') + .append(Integer.toHexString(System.identityHashCode(object))); + } + + // ToString + //----------------------------------------------------------------------- + /** + *

Gets the {@code toString} of an {@code Object} returning + * an empty string ("") if {@code null} input.

+ * + *
+     * ObjectUtils.toString(null)         = ""
+     * ObjectUtils.toString("")           = ""
+     * ObjectUtils.toString("bat")        = "bat"
+     * ObjectUtils.toString(Boolean.TRUE) = "true"
+     * 
+ * + * @see StringUtils#defaultString(String) + * @see String#valueOf(Object) + * @param obj the Object to {@code toString}, may be null + * @return the passed in Object's toString, or {@code ""} if {@code null} input + * @since 2.0 + * @deprecated this method has been replaced by {@code java.util.Objects.toString(Object)} in Java 7 and will be + * removed in future releases. Note however that said method will return "null" for null references, while this + * method returns and empty String. To preserve behavior use {@code java.util.Objects.toString(myObject, "")} + */ + @Deprecated + public static String toString(final Object obj) { + return obj == null ? StringUtils.EMPTY : obj.toString(); + } + + /** + *

Gets the {@code toString} of an {@code Object} returning + * a specified text if {@code null} input.

+ * + *
+     * ObjectUtils.toString(null, null)           = null
+     * ObjectUtils.toString(null, "null")         = "null"
+     * ObjectUtils.toString("", "null")           = ""
+     * ObjectUtils.toString("bat", "null")        = "bat"
+     * ObjectUtils.toString(Boolean.TRUE, "null") = "true"
+     * 
+ * + * @see StringUtils#defaultString(String,String) + * @see String#valueOf(Object) + * @param obj the Object to {@code toString}, may be null + * @param nullStr the String to return if {@code null} input, may be null + * @return the passed in Object's toString, or {@code nullStr} if {@code null} input + * @since 2.0 + * @deprecated this method has been replaced by {@code java.util.Objects.toString(Object, String)} in Java 7 and + * will be removed in future releases. + */ + @Deprecated + public static String toString(final Object obj, final String nullStr) { + return obj == null ? nullStr : obj.toString(); + } + + // Comparable + //----------------------------------------------------------------------- + /** + *

Null safe comparison of Comparables.

+ * + * @param type of the values processed by this method + * @param values the set of comparable values, may be null + * @return + *
    + *
  • If any objects are non-null and unequal, the lesser object. + *
  • If all objects are non-null and equal, the first. + *
  • If any of the comparables are null, the lesser of the non-null objects. + *
  • If all the comparables are null, null is returned. + *
+ */ + public static > T min(final T... values) { + T result = null; + if (values != null) { + for (final T value : values) { + if (compare(value, result, true) < 0) { + result = value; + } + } + } + return result; + } + + /** + *

Null safe comparison of Comparables.

+ * + * @param type of the values processed by this method + * @param values the set of comparable values, may be null + * @return + *
    + *
  • If any objects are non-null and unequal, the greater object. + *
  • If all objects are non-null and equal, the first. + *
  • If any of the comparables are null, the greater of the non-null objects. + *
  • If all the comparables are null, null is returned. + *
+ */ + public static > T max(final T... values) { + T result = null; + if (values != null) { + for (final T value : values) { + if (compare(value, result, false) > 0) { + result = value; + } + } + } + return result; + } + + /** + *

Null safe comparison of Comparables. + * {@code null} is assumed to be less than a non-{@code null} value.

+ * + * @param type of the values processed by this method + * @param c1 the first comparable, may be null + * @param c2 the second comparable, may be null + * @return a negative value if c1 < c2, zero if c1 = c2 + * and a positive value if c1 > c2 + */ + public static > int compare(final T c1, final T c2) { + return compare(c1, c2, false); + } + + /** + *

Null safe comparison of Comparables.

+ * + * @param type of the values processed by this method + * @param c1 the first comparable, may be null + * @param c2 the second comparable, may be null + * @param nullGreater if true {@code null} is considered greater + * than a non-{@code null} value or if false {@code null} is + * considered less than a Non-{@code null} value + * @return a negative value if c1 < c2, zero if c1 = c2 + * and a positive value if c1 > c2 + * @see java.util.Comparator#compare(Object, Object) + */ + public static > int compare(final T c1, final T c2, final boolean nullGreater) { + if (c1 == c2) { + return 0; + } else if (c1 == null) { + return nullGreater ? 1 : -1; + } else if (c2 == null) { + return nullGreater ? -1 : 1; + } + return c1.compareTo(c2); + } + + /** + * Find the "best guess" middle value among comparables. If there is an even + * number of total values, the lower of the two middle values will be returned. + * @param type of values processed by this method + * @param items to compare + * @return T at middle position + * @throws NullPointerException if items is {@code null} + * @throws IllegalArgumentException if items is empty or contains {@code null} values + * @since 3.0.1 + */ + public static > T median(final T... items) { + Validate.notEmpty(items); + Validate.noNullElements(items); + final TreeSet sort = new TreeSet(); + Collections.addAll(sort, items); + @SuppressWarnings("unchecked") //we know all items added were T instances + final + T result = (T) sort.toArray()[(sort.size() - 1) / 2]; + return result; + } + + /** + * Find the "best guess" middle value among comparables. If there is an even + * number of total values, the lower of the two middle values will be returned. + * @param type of values processed by this method + * @param comparator to use for comparisons + * @param items to compare + * @return T at middle position + * @throws NullPointerException if items or comparator is {@code null} + * @throws IllegalArgumentException if items is empty or contains {@code null} values + * @since 3.0.1 + */ + public static T median(final Comparator comparator, final T... items) { + Validate.notEmpty(items, "null/empty items"); + Validate.noNullElements(items); + Validate.notNull(comparator, "null comparator"); + final TreeSet sort = new TreeSet(comparator); + Collections.addAll(sort, items); + @SuppressWarnings("unchecked") //we know all items added were T instances + final + T result = (T) sort.toArray()[(sort.size() - 1) / 2]; + return result; + } + + // Mode + //----------------------------------------------------------------------- + /** + * Find the most frequently occurring item. + * + * @param type of values processed by this method + * @param items to check + * @return most populous T, {@code null} if non-unique or no items supplied + * @since 3.0.1 + */ + public static T mode(final T... items) { + if (ArrayUtils.isNotEmpty(items)) { + final HashMap occurrences = new HashMap(items.length); + for (final T t : items) { + final MutableInt count = occurrences.get(t); + if (count == null) { + occurrences.put(t, new MutableInt(1)); + } else { + count.increment(); + } + } + T result = null; + int max = 0; + for (final Map.Entry e : occurrences.entrySet()) { + final int cmp = e.getValue().intValue(); + if (cmp == max) { + result = null; + } else if (cmp > max) { + max = cmp; + result = e.getKey(); + } + } + return result; + } + return null; + } + + // cloning + //----------------------------------------------------------------------- + /** + *

Clone an object.

+ * + * @param the type of the object + * @param obj the object to clone, null returns null + * @return the clone if the object implements {@link Cloneable} otherwise {@code null} + * @throws CloneFailedException if the object is cloneable and the clone operation fails + * @since 3.0 + */ + public static T clone(final T obj) { + if (obj instanceof Cloneable) { + final Object result; + if (obj.getClass().isArray()) { + final Class componentType = obj.getClass().getComponentType(); + if (!componentType.isPrimitive()) { + result = ((Object[]) obj).clone(); + } else { + int length = Array.getLength(obj); + result = Array.newInstance(componentType, length); + while (length-- > 0) { + Array.set(result, length, Array.get(obj, length)); + } + } + } else { + try { + final Method clone = obj.getClass().getMethod("clone"); + result = clone.invoke(obj); + } catch (final NoSuchMethodException e) { + throw new CloneFailedException("Cloneable type " + + obj.getClass().getName() + + " has no clone method", e); + } catch (final IllegalAccessException e) { + throw new CloneFailedException("Cannot clone Cloneable type " + + obj.getClass().getName(), e); + } catch (final InvocationTargetException e) { + throw new CloneFailedException("Exception cloning Cloneable type " + + obj.getClass().getName(), e.getCause()); + } + } + @SuppressWarnings("unchecked") // OK because input is of type T + final T checked = (T) result; + return checked; + } + + return null; + } + + /** + *

Clone an object if possible.

+ * + *

This method is similar to {@link #clone(Object)}, but will return the provided + * instance as the return value instead of {@code null} if the instance + * is not cloneable. This is more convenient if the caller uses different + * implementations (e.g. of a service) and some of the implementations do not allow concurrent + * processing or have state. In such cases the implementation can simply provide a proper + * clone implementation and the caller's code does not have to change.

+ * + * @param the type of the object + * @param obj the object to clone, null returns null + * @return the clone if the object implements {@link Cloneable} otherwise the object itself + * @throws CloneFailedException if the object is cloneable and the clone operation fails + * @since 3.0 + */ + public static T cloneIfPossible(final T obj) { + final T clone = clone(obj); + return clone == null ? obj : clone; + } + + // Null + //----------------------------------------------------------------------- + /** + *

Class used as a null placeholder where {@code null} + * has another meaning.

+ * + *

For example, in a {@code HashMap} the + * {@link java.util.HashMap#get(java.lang.Object)} method returns + * {@code null} if the {@code Map} contains {@code null} or if there is + * no matching key. The {@code Null} placeholder can be used to distinguish + * between these two cases.

+ * + *

Another example is {@code Hashtable}, where {@code null} + * cannot be stored.

+ */ + public static class Null implements Serializable { + /** + * Required for serialization support. Declare serialization compatibility with Commons Lang 1.0 + * + * @see java.io.Serializable + */ + private static final long serialVersionUID = 7092611880189329093L; + + /** + * Restricted constructor - singleton. + */ + Null() { + super(); + } + + /** + *

Ensure singleton.

+ * + * @return the singleton value + */ + private Object readResolve() { + return ObjectUtils.NULL; + } + } + + + // Constants (LANG-816): + /* + These methods ensure constants are not inlined by javac. + For example, typically a developer might declare a constant like so: + + public final static int MAGIC_NUMBER = 5; + + Should a different jar file refer to this, and the MAGIC_NUMBER + is changed a later date (e.g., MAGIC_NUMBER = 6), the different jar + file will need to recompile itself. This is because javac + typically inlines the primitive or String constant directly into + the bytecode, and removes the reference to the MAGIC_NUMBER field. + + To help the other jar (so that it does not need to recompile + when constants are changed) the original developer can declare + their constant using one of the CONST() utility methods, instead: + + public final static int MAGIC_NUMBER = CONST(5); + */ + + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static boolean MAGIC_FLAG = ObjectUtils.CONST(true);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the boolean value to return + * @return the boolean v, unchanged + * @since 3.2 + */ + public static boolean CONST(final boolean v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static byte MAGIC_BYTE = ObjectUtils.CONST((byte) 127);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the byte value to return + * @return the byte v, unchanged + * @since 3.2 + */ + public static byte CONST(final byte v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static byte MAGIC_BYTE = ObjectUtils.CONST_BYTE(127);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the byte literal (as an int) value to return + * @throws IllegalArgumentException if the value passed to v + * is larger than a byte, that is, smaller than -128 or + * larger than 127. + * @return the byte v, unchanged + * @since 3.2 + */ + public static byte CONST_BYTE(final int v) throws IllegalArgumentException { + if (v < Byte.MIN_VALUE || v > Byte.MAX_VALUE) { + throw new IllegalArgumentException("Supplied value must be a valid byte literal between -128 and 127: [" + v + "]"); + } + return (byte) v; + } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static char MAGIC_CHAR = ObjectUtils.CONST('a');
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the char value to return + * @return the char v, unchanged + * @since 3.2 + */ + public static char CONST(final char v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static short MAGIC_SHORT = ObjectUtils.CONST((short) 123);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the short value to return + * @return the short v, unchanged + * @since 3.2 + */ + public static short CONST(final short v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static short MAGIC_SHORT = ObjectUtils.CONST_SHORT(127);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the short literal (as an int) value to return + * @throws IllegalArgumentException if the value passed to v + * is larger than a short, that is, smaller than -32768 or + * larger than 32767. + * @return the byte v, unchanged + * @since 3.2 + */ + public static short CONST_SHORT(final int v) throws IllegalArgumentException { + if (v < Short.MIN_VALUE || v > Short.MAX_VALUE) { + throw new IllegalArgumentException("Supplied value must be a valid byte literal between -32768 and 32767: [" + v + "]"); + } + return (short) v; + } + + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static int MAGIC_INT = ObjectUtils.CONST(123);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the int value to return + * @return the int v, unchanged + * @since 3.2 + */ + public static int CONST(final int v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static long MAGIC_LONG = ObjectUtils.CONST(123L);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the long value to return + * @return the long v, unchanged + * @since 3.2 + */ + public static long CONST(final long v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static float MAGIC_FLOAT = ObjectUtils.CONST(1.0f);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the float value to return + * @return the float v, unchanged + * @since 3.2 + */ + public static float CONST(final float v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static double MAGIC_DOUBLE = ObjectUtils.CONST(1.0);
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param v the double value to return + * @return the double v, unchanged + * @since 3.2 + */ + public static double CONST(final double v) { return v; } + + /** + * This method returns the provided value unchanged. + * This can prevent javac from inlining a constant + * field, e.g., + * + *
+     *     public final static String MAGIC_STRING = ObjectUtils.CONST("abc");
+     * 
+ * + * This way any jars that refer to this field do not + * have to recompile themselves if the field's value + * changes at some future date. + * + * @param the Object type + * @param v the genericized Object value to return (typically a String). + * @return the genericized Object v, unchanged (typically a String). + * @since 3.2 + */ + public static T CONST(final T v) { return v; } + +} diff --git a/Java/commons-lang-ObjectUtils_95/metadata.json b/Java/commons-lang-ObjectUtils_95/metadata.json new file mode 100644 index 000000000..2928087dd --- /dev/null +++ b/Java/commons-lang-ObjectUtils_95/metadata.json @@ -0,0 +1,21 @@ +{ + "language": "java", + "id": "commons-lang-ObjectUtils_95", + "buggyPath": ".", + "referencePath": null, + "buildCommand": "mvn package -V -B -Denforcer.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true -Drat.skip=true -Dlicense.skip=true -Dfindbugs.skip=true -Dgpg.skip=true -Dskip.npm=true -Dskip.gulp=true -Dskip.bower=true -Drat.numUnapprovedLicenses=100 -DskipTests=true -DskipITs=true -Dtest=None -DfailIfNoTests=false", + "testCommand": "mvn test -V -B -Denforcer.skip=true -Dcheckstyle.skip=true -Dcobertura.skip=true -Drat.skip=true -Dlicense.skip=true -Dfindbugs.skip=true -Dgpg.skip=true -Dskip.npm=true -Dskip.gulp=true -Dskip.bower=true -Drat.numUnapprovedLicenses=100", + "categories": [ + "safety", + "npe" + ], + "npe": { + "filepath": "src/main/java/org/apache/commons/lang3/ObjectUtils.java", + "line": 117, + "npe_method": "defaultIfNull", + "deref_field": "object", + "npe_class": "ObjectUtils", + "repo": "commons-lang", + "bug_id": "ObjectUtils_95" + } +} diff --git a/Java/commons-lang-ObjectUtils_95/npe.json b/Java/commons-lang-ObjectUtils_95/npe.json new file mode 100644 index 000000000..d9f783fe0 --- /dev/null +++ b/Java/commons-lang-ObjectUtils_95/npe.json @@ -0,0 +1,7 @@ +{ + "filepath": "src/main/java/org/apache/commons/lang3/ObjectUtils.java", + "line": 117, + "npe_method": "defaultIfNull", + "deref_field": "object", + "npe_class": "ObjectUtils" +} \ No newline at end of file