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
.
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
.
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
.
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
.
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
.
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
.
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
.
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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.
Gets the minimum of three int
values.
Gets the minimum of three short
values.
Gets the minimum of three byte
values.
Gets the minimum of three double
values.
If any value is NaN
, NaN
is
+ * returned. Infinity is handled.
Gets the minimum of three float
values.
If any value is NaN
, NaN
is
+ * returned. Infinity is handled.
Gets the maximum of three long
values.
Gets the maximum of three int
values.
Gets the maximum of three short
values.
Gets the maximum of three byte
values.
Gets the maximum of three double
values.
If any value is NaN
, NaN
is
+ * returned. Infinity is handled.
Gets the maximum of three float
values.
If any value is NaN
, NaN
is
+ * returned. Infinity is handled.
Checks whether the String
contains only
+ * digit characters.
Null
and empty String will return
+ * false
.
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
.
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
.
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
.
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
.
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
.
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
.
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
.
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
.
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
.
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
.
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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.
Gets the minimum of three int
values.
Gets the minimum of three short
values.
Gets the minimum of three byte
values.
Gets the minimum of three double
values.
If any value is NaN
, NaN
is
+ * returned. Infinity is handled.
Gets the minimum of three float
values.
If any value is NaN
, NaN
is
+ * returned. Infinity is handled.
Gets the maximum of three long
values.
Gets the maximum of three int
values.
Gets the maximum of three short
values.
Gets the maximum of three byte
values.
Gets the maximum of three double
values.
If any value is NaN
, NaN
is
+ * returned. Infinity is handled.
Gets the maximum of three float
values.
If any value is NaN
, NaN
is
+ * returned. Infinity is handled.
Checks whether the String
contains only
+ * digit characters.
Null
and empty String will return
+ * false
.
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
.
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
.
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
.
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
.
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
.
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
.
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
.
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
.
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
.
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
.
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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.
Gets the minimum of three int
values.
Gets the minimum of three short
values.
Gets the minimum of three byte
values.
Gets the minimum of three double
values.
If any value is NaN
, NaN
is
+ * returned. Infinity is handled.
Gets the minimum of three float
values.
If any value is NaN
, NaN
is
+ * returned. Infinity is handled.
Gets the maximum of three long
values.
Gets the maximum of three int
values.
Gets the maximum of three short
values.
Gets the maximum of three byte
values.
Gets the maximum of three double
values.
If any value is NaN
, NaN
is
+ * returned. Infinity is handled.
Gets the maximum of three float
values.
If any value is NaN
, NaN
is
+ * returned. Infinity is handled.
Checks whether the String
contains only
+ * digit characters.
Null
and empty String will return
+ * false
.
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
.
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
.
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
.
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
.
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
.
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
.
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
.
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
.
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
.
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
.
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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.
Gets the minimum of three int
values.
Gets the minimum of three short
values.
Gets the minimum of three byte
values.
Gets the minimum of three double
values.
If any value is NaN
, NaN
is
+ * returned. Infinity is handled.
Gets the minimum of three float
values.
If any value is NaN
, NaN
is
+ * returned. Infinity is handled.
Gets the maximum of three long
values.
Gets the maximum of three int
values.
Gets the maximum of three short
values.
Gets the maximum of three byte
values.
Gets the maximum of three double
values.
If any value is NaN
, NaN
is
+ * returned. Infinity is handled.
Gets the maximum of three float
values.
If any value is NaN
, NaN
is
+ * returned. Infinity is handled.
Checks whether the String
contains only
+ * digit characters.
Null
and empty String will return
+ * false
.
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
.
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
.
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
.
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
.
null
+ */
+/**
+ * Utility method for {@link #createNumber(java.lang.String)}.
+ * + *Returns true
if s is null
.
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
.
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
.
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
.
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
.
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
.
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
.
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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.
Gets the minimum of three int
values.
Gets the minimum of three short
values.
Gets the minimum of three byte
values.
Gets the minimum of three double
values.
If any value is NaN
, NaN
is
+ * returned. Infinity is handled.
Gets the minimum of three float
values.
If any value is NaN
, NaN
is
+ * returned. Infinity is handled.
Gets the maximum of three long
values.
Gets the maximum of three int
values.
Gets the maximum of three short
values.
Gets the maximum of three byte
values.
Gets the maximum of three double
values.
If any value is NaN
, NaN
is
+ * returned. Infinity is handled.
Gets the maximum of three float
values.
If any value is NaN
, NaN
is
+ * returned. Infinity is handled.
Checks whether the String
contains only
+ * digit characters.
Null
and empty String will return
+ * false
.
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
.
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
.
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
.
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
.
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
.
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
.
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
.
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
.
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
.
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
.
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
.
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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.
Gets the minimum of three int
values.
Gets the minimum of three short
values.
Gets the minimum of three byte
values.
Gets the minimum of three double
values.
If any value is NaN
, NaN
is
+ * returned. Infinity is handled.
Gets the minimum of three float
values.
If any value is NaN
, NaN
is
+ * returned. Infinity is handled.
Gets the maximum of three long
values.
Gets the maximum of three int
values.
Gets the maximum of three short
values.
Gets the maximum of three byte
values.
Gets the maximum of three double
values.
If any value is NaN
, NaN
is
+ * returned. Infinity is handled.
Gets the maximum of three float
values.
If any value is NaN
, NaN
is
+ * returned. Infinity is handled.
Checks whether the String
contains only
+ * digit characters.
Null
and empty String will return
+ * false
.
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
.
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
.
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
.
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
.
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
.
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
.
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
.
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
.
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
.
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
.
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
.
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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.
Gets the minimum of three int
values.
Gets the minimum of three short
values.
Gets the minimum of three byte
values.
Gets the minimum of three double
values.
If any value is NaN
, NaN
is
+ * returned. Infinity is handled.
Gets the minimum of three float
values.
If any value is NaN
, NaN
is
+ * returned. Infinity is handled.
Gets the maximum of three long
values.
Gets the maximum of three int
values.
Gets the maximum of three short
values.
Gets the maximum of three byte
values.
Gets the maximum of three double
values.
If any value is NaN
, NaN
is
+ * returned. Infinity is handled.
Gets the maximum of three float
values.
If any value is NaN
, NaN
is
+ * returned. Infinity is handled.
Checks whether the String
contains only
+ * digit characters.
Null
and empty String will return
+ * false
.
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
.
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
.
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
.
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
.
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
.
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
.
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
.
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
.
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
.
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
.
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
.
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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.
Gets the minimum of three int
values.
Gets the minimum of three short
values.
Gets the minimum of three byte
values.
Gets the minimum of three double
values.
If any value is NaN
, NaN
is
+ * returned. Infinity is handled.
Gets the minimum of three float
values.
If any value is NaN
, NaN
is
+ * returned. Infinity is handled.
Gets the maximum of three long
values.
Gets the maximum of three int
values.
Gets the maximum of three short
values.
Gets the maximum of three byte
values.
Gets the maximum of three double
values.
If any value is NaN
, NaN
is
+ * returned. Infinity is handled.
Gets the maximum of three float
values.
If any value is NaN
, NaN
is
+ * returned. Infinity is handled.
Checks whether the String
contains only
+ * digit characters.
Null
and empty String will return
+ * false
.
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
.
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
.
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
.
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
.
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
.
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
.
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
.
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
.
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
.
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
.
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
.
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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.
Gets the minimum of three int
values.
Gets the minimum of three short
values.
Gets the minimum of three byte
values.
Gets the minimum of three double
values.
If any value is NaN
, NaN
is
+ * returned. Infinity is handled.
Gets the minimum of three float
values.
If any value is NaN
, NaN
is
+ * returned. Infinity is handled.
Gets the maximum of three long
values.
Gets the maximum of three int
values.
Gets the maximum of three short
values.
Gets the maximum of three byte
values.
Gets the maximum of three double
values.
If any value is NaN
, NaN
is
+ * returned. Infinity is handled.
Gets the maximum of three float
values.
If any value is NaN
, NaN
is
+ * returned. Infinity is handled.
Checks whether the String
contains only
+ * digit characters.
Null
and empty String will return
+ * false
.
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
.
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
.
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
.
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
.
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
.
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
.
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
.
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
.
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
.
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
.
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
.
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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.
Gets the minimum of three int
values.
Gets the minimum of three short
values.
Gets the minimum of three byte
values.
Gets the minimum of three double
values.
If any value is NaN
, NaN
is
+ * returned. Infinity is handled.
Gets the minimum of three float
values.
If any value is NaN
, NaN
is
+ * returned. Infinity is handled.
Gets the maximum of three long
values.
Gets the maximum of three int
values.
Gets the maximum of three short
values.
Gets the maximum of three byte
values.
Gets the maximum of three double
values.
If any value is NaN
, NaN
is
+ * returned. Infinity is handled.
Gets the maximum of three float
values.
If any value is NaN
, NaN
is
+ * returned. Infinity is handled.
Checks whether the String
contains only
+ * digit characters.
Null
and empty String will return
+ * false
.
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
.
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
.
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
.
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
.
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
.
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
.
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
.
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
.
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
.
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
.
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
.
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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 ifarray
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.
Gets the minimum of three int
values.
Gets the minimum of three short
values.
Gets the minimum of three byte
values.
Gets the minimum of three double
values.
If any value is NaN
, NaN
is
+ * returned. Infinity is handled.
Gets the minimum of three float
values.
If any value is NaN
, NaN
is
+ * returned. Infinity is handled.
Gets the maximum of three long
values.
Gets the maximum of three int
values.
Gets the maximum of three short
values.
Gets the maximum of three byte
values.
Gets the maximum of three double
values.
If any value is NaN
, NaN
is
+ * returned. Infinity is handled.
Gets the maximum of three float
values.
If any value is NaN
, NaN
is
+ * returned. Infinity is handled.
Checks whether the String
contains only
+ * digit characters.
Null
and empty String will return
+ * false
.
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
.
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
.
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
.
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.
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.
+ * + *input | + *wrapLength | + *result | + *
---|---|---|
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" | + *
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.
+ * + *input | + *wrapLenght | + *newLineString | + *wrapLongWords | + *result | + *
---|---|---|---|---|
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." | + *20 | + *null | + *true/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" | + *
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.
+ * + *input | + *wrapLenght | + *newLineString | + *wrapLongWords | + *wrapOn | + *result | + *
---|---|---|---|---|---|
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." | + *20 | + *null | + *true/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" | + *
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.
+ * + *input | + *wrapLenght | + *newLineString | + *wrapLongWords | + *wrapOn | + *result | + *
---|---|---|---|---|---|
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." | + *20 | + *null | + *true/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" | + *
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.
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.
+ * + *input | + *wrapLength | + *result | + *
---|---|---|
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" | + *
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.
+ * + *input | + *wrapLenght | + *newLineString | + *wrapLongWords | + *result | + *
---|---|---|---|---|
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." | + *20 | + *null | + *true/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" | + *
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.
+ * + *input | + *wrapLenght | + *newLineString | + *wrapLongWords | + *wrapOn | + *result | + *
---|---|---|---|---|---|
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." | + *20 | + *null | + *true/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" | + *
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.
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.
+ * + *input | + *wrapLength | + *result | + *
---|---|---|
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" | + *
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.
+ * + *input | + *wrapLenght | + *newLineString | + *wrapLongWords | + *result | + *
---|---|---|---|---|
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." | + *20 | + *null | + *true/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" | + *
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.
+ * + *input | + *wrapLenght | + *newLineString | + *wrapLongWords | + *wrapOn | + *result | + *
---|---|---|---|---|---|
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." | + *20 | + *null | + *true/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" | + *
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 RangeObtains 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.
+ * + * @paramObtains 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.
+ * + * @paramObtains 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.
+ * + * @paramObtains 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.
+ * + * @paramGets 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 ComparatorWhether 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 RangeChecks 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 RangeChecks 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 RangeChecks 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 RangeCompares 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 + RangeGets 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 RangeObtains 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.
+ * + * @paramObtains 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.
+ * + * @paramObtains 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.
+ * + * @paramObtains 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.
+ * + * @paramGets 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 ComparatorWhether 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 RangeChecks 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 RangeChecks 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 RangeChecks 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 RangeCompares 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 + RangeGets 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 RangeObtains 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.
+ * + * @paramObtains 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.
+ * + * @paramObtains 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.
+ * + * @paramObtains 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.
+ * + * @paramGets 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 ComparatorWhether 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 RangeChecks 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 RangeChecks 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 RangeChecks 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 RangeCompares 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 + RangeGets 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 RangeObtains 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.
+ * + * @paramObtains 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.
+ * + * @paramObtains 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.
+ * + * @paramObtains 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.
+ * + * @paramGets 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 ComparatorWhether 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 RangeChecks 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 RangeChecks 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 RangeChecks 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 RangeCompares 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 + RangeGets 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 RangeObtains 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.
+ * + * @paramObtains 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.
+ * + * @paramObtains 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.
+ * + * @paramObtains 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.
+ * + * @paramGets 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 ComparatorWhether 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 RangeChecks 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 RangeChecks 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 RangeChecks 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 RangeCompares 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 + RangeGets 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 RangeObtains 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.
+ * + * @paramObtains 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.
+ * + * @paramObtains 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.
+ * + * @paramObtains 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.
+ * + * @paramGets 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 ComparatorWhether 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 RangeChecks 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 RangeChecks 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 RangeChecks 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 RangeCompares 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 + RangeGets 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 RangeObtains 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.
+ * + * @paramObtains 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.
+ * + * @paramObtains 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.
+ * + * @paramObtains 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.
+ * + * @paramGets 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 ComparatorWhether 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.RangeChecks 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 RangeChecks 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 RangeChecks 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 RangeCompares 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 + RangeGets 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 RangeObtains 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.
+ * + * @paramObtains 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.
+ * + * @paramObtains 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.
+ * + * @paramObtains 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.
+ * + * @paramGets 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 ComparatorWhether 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 RangeChecks 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.RangeChecks 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 RangeChecks 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 RangeCompares 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 + RangeGets 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 RangeObtains 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.
+ * + * @paramObtains 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.
+ * + * @paramObtains 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.
+ * + * @paramObtains 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.
+ * + * @paramGets 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 ComparatorWhether 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 RangeChecks 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 RangeChecks 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.RangeChecks 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 RangeCompares 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 + RangeGets 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 RangeObtains 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.
+ * + * @paramObtains 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.
+ * + * @paramObtains 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