output
stringlengths 64
73.2k
| input
stringlengths 208
73.3k
| instruction
stringclasses 1
value |
---|---|---|
#fixed code
@Test
public void testLong_LittleEndian() throws Exception {
assertArrayEquals(new byte[]{0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01}, BeginBin().ByteOrder(JBBPByteOrder.LITTLE_ENDIAN).Long(0x0102030405060708L).End().toByteArray());
} | #vulnerable code
@Test
public void testLong_LittleEndian() throws Exception {
assertArrayEquals(new byte[]{0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01}, binStart().ByteOrder(JBBPByteOrder.LITTLE_ENDIAN).Long(0x0102030405060708L).end().toByteArray());
}
#location 3
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public int readBits(final JBBPBitNumber numOfBitsToRead) throws IOException {
int result;
final int numOfBitsAsNumber = numOfBitsToRead.getBitNumber();
if (this.bitsInBuffer == 0 && numOfBitsAsNumber == 8) {
result = this.readByteFromStream();
this.byteCounter++;
return result;
}
else {
result = 0;
if (numOfBitsAsNumber == this.bitsInBuffer) {
result = this.bitBuffer;
this.bitBuffer = 0;
this.bitsInBuffer = 0;
if (numOfBitsAsNumber == 8) {
this.byteCounter++;
}
return result;
}
int i = numOfBitsAsNumber;
int theBitBuffer = this.bitBuffer;
int theBitBufferCounter = this.bitsInBuffer;
while (i > 0) {
if (theBitBufferCounter == 0) {
final int nextByte = this.readByteFromStream();
if (nextByte < 0) {
if (i == numOfBitsAsNumber) {
return nextByte;
}
else {
break;
}
}
else {
theBitBuffer = nextByte;
theBitBufferCounter = 8;
this.byteCounter++;
}
}
result = (result << 1) | (theBitBuffer & 1);
theBitBuffer >>= 1;
theBitBufferCounter--;
i--;
}
this.bitBuffer = theBitBuffer;
this.bitsInBuffer = theBitBufferCounter;
return (JBBPUtils.reverseByte((byte) result) & 0xFF) >> (8 - (numOfBitsAsNumber - i));
}
} | #vulnerable code
public int readBits(final JBBPBitNumber numOfBitsToRead) throws IOException {
int result;
final int numOfBitsAsNumber = numOfBitsToRead.getBitNumber();
if (this.bitsInBuffer == 0 && numOfBitsAsNumber == 8) {
result = this.readByteFromStream();
return result;
}
else {
result = 0;
if (numOfBitsAsNumber == this.bitsInBuffer){
result = this.bitBuffer;
this.bitBuffer = 0;
this.bitsInBuffer = 0;
return result;
}
int i = numOfBitsAsNumber;
int theBitBuffer = this.bitBuffer;
int theBitBufferCounter = this.bitsInBuffer;
while (i > 0) {
if (theBitBufferCounter == 0) {
final int nextByte = this.readByteFromStream();
if (nextByte < 0) {
if (i == numOfBitsAsNumber) {
return nextByte;
}
else {
break;
}
}
else {
theBitBuffer = nextByte;
theBitBufferCounter = 8;
}
}
result = (result << 1) | (theBitBuffer & 1);
theBitBuffer >>= 1;
theBitBufferCounter--;
i--;
}
this.bitBuffer = theBitBuffer;
this.bitsInBuffer = theBitBufferCounter;
return (JBBPUtils.reverseByte((byte) result) & 0xFF) >> (8 - (numOfBitsAsNumber - i));
}
}
#location 26
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testComplexWriting_1() throws Exception {
final byte [] array =
BeginBin().
Bit(1, 2, 3, 0).
Bit(true, false, true).
Align().
Byte(5).
Short(1, 2, 3, 4, 5).
Bool(true, false, true, true).
Int(0xABCDEF23, 0xCAFEBABE).
Long(0x123456789ABCDEF1L, 0x212356239091AB32L).
End().toByteArray();
assertEquals(40, array.length);
assertArrayEquals(new byte[]{
(byte) 0x55, 5, 0, 1, 0, 2, 0, 3, 0, 4, 0, 5, 1, 0, 1, 1,
(byte) 0xAB, (byte) 0xCD, (byte) 0xEF, 0x23, (byte) 0xCA, (byte) 0xFE, (byte) 0xBA, (byte) 0xBE,
0x12, 0x34, 0x56, 0x78, (byte) 0x9A, (byte) 0xBC, (byte) 0xDE, (byte) 0xF1, 0x21, 0x23, 0x56, 0x23, (byte) 0x90, (byte) 0x91, (byte) 0xAB, 0x32
}, array);
} | #vulnerable code
@Test
public void testComplexWriting_1() throws Exception {
final ByteArrayOutputStream buffer = new ByteArrayOutputStream(16384);
final JBBPOut begin = new JBBPOut(buffer);
begin.
Bit(1, 2, 3, 0).
Bit(true, false, true).
Align().
Byte(5).
Short(1, 2, 3, 4, 5).
Bool(true, false, true, true).
Int(0xABCDEF23, 0xCAFEBABE).
Long(0x123456789ABCDEF1L, 0x212356239091AB32L).
end();
final byte[] array = buffer.toByteArray();
assertEquals(40, array.length);
assertArrayEquals(new byte[]{
(byte) 0x55, 5, 0, 1, 0, 2, 0, 3, 0, 4, 0, 5, 1, 0, 1, 1,
(byte) 0xAB, (byte) 0xCD, (byte) 0xEF, 0x23, (byte) 0xCA, (byte) 0xFE, (byte) 0xBA, (byte) 0xBE,
0x12, 0x34, 0x56, 0x78, (byte) 0x9A, (byte) 0xBC, (byte) 0xDE, (byte) 0xF1, 0x21, 0x23, 0x56, 0x23, (byte) 0x90, (byte) 0x91, (byte) 0xAB, 0x32
}, array);
}
#location 12
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testBit() throws Exception {
assertArrayEquals(new byte[]{1}, BeginBin().Bit(1).End().toByteArray());
} | #vulnerable code
@Test
public void testBit() throws Exception {
assertArrayEquals(new byte[]{1}, binStart().Bit(1).end().toByteArray());
}
#location 3
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public JBBPOut Bin(final Object object) throws IOException {
if (this.processCommands) {
JBBPUtils.assertNotNull(object, "Object must not be null");
Field[] orderedFields = null;
final Map<Class<?>, Field[]> fieldz;
if (cachedFields == null) {
fieldz = new HashMap<Class<?>, Field[]>();
cachedFields = fieldz;
}
else {
fieldz = cachedFields;
synchronized (fieldz) {
orderedFields = fieldz.get(object.getClass());
}
}
if (orderedFields == null) {
// find out the order of fields and fields which should be serialized
final List<Class<?>> listOfClassHierarchy = new ArrayList<Class<?>>();
final List<OrderedField> fields = new ArrayList<OrderedField>();
Class<?> current = object.getClass();
while (current != java.lang.Object.class) {
listOfClassHierarchy.add(current);
current = current.getSuperclass();
}
for (int i = listOfClassHierarchy.size() - 1; i >= 0; i--) {
final Class<?> clazzToProcess = listOfClassHierarchy.get(i);
final Bin clazzAnno = clazzToProcess.getAnnotation(Bin.class);
for (final Field f : clazzToProcess.getDeclaredFields()) {
f.setAccessible(true);
if (Modifier.isTransient(f.getModifiers())) {
continue;
}
Bin fieldAnno = f.getAnnotation(Bin.class);
fieldAnno = fieldAnno == null ? clazzAnno : fieldAnno;
if (fieldAnno == null) {
continue;
}
fields.add(new OrderedField(fieldAnno.order(), f));
}
}
Collections.sort(fields);
orderedFields = new Field[fields.size()];
for (int i = 0; i < fields.size(); i++) {
orderedFields[i] = fields.get(i).field;
}
synchronized (fieldz) {
fieldz.put(object.getClass(), orderedFields);
}
}
for (final Field f : orderedFields) {
Bin binAnno = f.getAnnotation(Bin.class);
if (binAnno == null) {
binAnno = f.getDeclaringClass().getAnnotation(Bin.class);
if (binAnno == null) {
throw new JBBPException("Can't find any Bin annotation to use for " + f + " field");
}
}
writeObjectField(object, f, binAnno);
}
}
return this;
} | #vulnerable code
public JBBPOut Bin(final Object object) throws IOException {
if (this.processCommands) {
Field[] orderedFields = null;
final Map<Class<?>, Field[]> fieldz;
if (cachedFields == null) {
fieldz = new HashMap<Class<?>, Field[]>();
cachedFields = fieldz;
}
else {
fieldz = cachedFields;
synchronized (fieldz) {
orderedFields = fieldz.get(object.getClass());
}
}
if (orderedFields == null) {
// find out the order of fields and fields which should be serialized
final List<Class<?>> listOfClassHierarchy = new ArrayList<Class<?>>();
final class OrderedField implements Comparable<OrderedField> {
final int order;
final Field field;
OrderedField(final int order, final Field field) {
this.order = order;
this.field = field;
}
public int compareTo(final OrderedField o) {
return this.order < o.order ? -1 : 1;
}
}
final List<OrderedField> fields = new ArrayList<OrderedField>();
Class<?> current = object.getClass();
while (current != java.lang.Object.class) {
listOfClassHierarchy.add(current);
current = current.getSuperclass();
}
for (int i = listOfClassHierarchy.size() - 1; i >= 0; i--) {
final Class<?> clazzToProcess = listOfClassHierarchy.get(i);
final Bin clazzAnno = clazzToProcess.getAnnotation(Bin.class);
for (final Field f : clazzToProcess.getDeclaredFields()) {
f.setAccessible(true);
if (Modifier.isTransient(f.getModifiers())) {
continue;
}
Bin fieldAnno = f.getAnnotation(Bin.class);
fieldAnno = fieldAnno == null ? clazzAnno : fieldAnno;
if (fieldAnno == null) {
continue;
}
fields.add(new OrderedField(fieldAnno.order(), f));
}
}
Collections.sort(fields);
orderedFields = new Field[fields.size()];
for (int i = 0; i < fields.size(); i++) {
orderedFields[i] = fields.get(i).field;
}
synchronized (fieldz) {
fieldz.put(object.getClass(), orderedFields);
}
}
for (final Field f : orderedFields) {
Bin binAnno = f.getAnnotation(Bin.class);
if (binAnno == null) {
binAnno = f.getDeclaringClass().getAnnotation(Bin.class);
if (binAnno == null) {
throw new JBBPException("Can't find any Bin annotation to use for " + f + " field");
}
}
writeObjectField(object, f, binAnno);
}
}
return this;
}
#location 83
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testBitArrayAsInts() throws Exception {
assertArrayEquals(new byte[]{(byte) 0xE3}, BeginBin().Bit(1, 3, 0, 2, 4, 1, 3, 7).End().toByteArray());
assertArrayEquals(new byte[]{(byte) 0x0B}, BeginBin().Bit(1, 3, 0, 7).End().toByteArray());
} | #vulnerable code
@Test
public void testBitArrayAsInts() throws Exception {
assertArrayEquals(new byte[]{(byte) 0xE3}, binStart().Bit(1, 3, 0, 2, 4, 1, 3, 7).end().toByteArray());
assertArrayEquals(new byte[]{(byte) 0x0B}, binStart().Bit(1, 3, 0, 7).end().toByteArray());
}
#location 3
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testShort_LittleEndian() throws Exception {
assertArrayEquals(new byte []{0x02,01}, BeginBin().ByteOrder(JBBPByteOrder.LITTLE_ENDIAN).Short(0x0102).End().toByteArray());
} | #vulnerable code
@Test
public void testShort_LittleEndian() throws Exception {
assertArrayEquals(new byte []{0x02,01}, binStart().ByteOrder(JBBPByteOrder.LITTLE_ENDIAN).Short(0x0102).end().toByteArray());
}
#location 3
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testExceptionForOperatioOverEndedProcess() throws Exception {
final JBBPOut out = BeginBin();
out.ByteOrder(JBBPByteOrder.BIG_ENDIAN).Long(0x0102030405060708L).End();
try{
out.Align();
fail("Must throw ISE");
}catch(IllegalStateException ex){
}
try{
out.Align(3);
fail("Must throw ISE");
}catch(IllegalStateException ex){
}
try{
out.Bit(true);
fail("Must throw ISE");
}catch(IllegalStateException ex){
}
try{
out.Bit(true,false);
fail("Must throw ISE");
}catch(IllegalStateException ex){
}
try{
out.Bit((byte)34);
fail("Must throw ISE");
}catch(IllegalStateException ex){
}
try{
out.Bit((byte)34,(byte)12);
fail("Must throw ISE");
}catch(IllegalStateException ex){
}
try{
out.Bit(34,12);
fail("Must throw ISE");
}catch(IllegalStateException ex){
}
try{
out.Bits(JBBPNumberOfBits.BITS_3, 12);
fail("Must throw ISE");
}catch(IllegalStateException ex){
}
try{
out.Bits(JBBPNumberOfBits.BITS_3, 12,13,14);
fail("Must throw ISE");
}catch(IllegalStateException ex){
}
try{
out.Bits(JBBPNumberOfBits.BITS_3, (byte)1,(byte)2,(byte)3);
fail("Must throw ISE");
}catch(IllegalStateException ex){
}
try{
out.Bool(true);
fail("Must throw ISE");
}catch(IllegalStateException ex){
}
try{
out.Bool(true,false);
fail("Must throw ISE");
}catch(IllegalStateException ex){
}
try{
out.Byte((byte)1,(byte)2,(byte)3);
fail("Must throw ISE");
}catch(IllegalStateException ex){
}
try{
out.Byte(1);
fail("Must throw ISE");
}catch(IllegalStateException ex){
}
try{
out.Byte(1,2,3);
fail("Must throw ISE");
}catch(IllegalStateException ex){
}
try{
out.ByteOrder(JBBPByteOrder.BIG_ENDIAN);
fail("Must throw ISE");
}catch(IllegalStateException ex){
}
try{
out.Flush();
fail("Must throw ISE");
}catch(IllegalStateException ex){
}
try{
out.Int(1);
fail("Must throw ISE");
}catch(IllegalStateException ex){
}
try{
out.Int(1,2);
fail("Must throw ISE");
}catch(IllegalStateException ex){
}
try{
out.Long(1L);
fail("Must throw ISE");
}catch(IllegalStateException ex){
}
try{
out.Long(1L,2L);
fail("Must throw ISE");
}catch(IllegalStateException ex){
}
try{
out.Short(1);
fail("Must throw ISE");
}catch(IllegalStateException ex){
}
try{
out.Short(1,2,3);
fail("Must throw ISE");
}catch(IllegalStateException ex){
}
try{
out.Short((short)1,(short)2,(short)3);
fail("Must throw ISE");
}catch(IllegalStateException ex){
}
try{
out.End();
fail("Must throw ISE");
}catch(IllegalStateException ex){
}
} | #vulnerable code
@Test
public void testExceptionForOperatioOverEndedProcess() throws Exception {
final JBBPOut out = binStart();
out.ByteOrder(JBBPByteOrder.BIG_ENDIAN).Long(0x0102030405060708L).end();
try{
out.Align();
fail("Must throw ISE");
}catch(IllegalStateException ex){
}
try{
out.Align(3);
fail("Must throw ISE");
}catch(IllegalStateException ex){
}
try{
out.Bit(true);
fail("Must throw ISE");
}catch(IllegalStateException ex){
}
try{
out.Bit(true,false);
fail("Must throw ISE");
}catch(IllegalStateException ex){
}
try{
out.Bit((byte)34);
fail("Must throw ISE");
}catch(IllegalStateException ex){
}
try{
out.Bit((byte)34,(byte)12);
fail("Must throw ISE");
}catch(IllegalStateException ex){
}
try{
out.Bit(34,12);
fail("Must throw ISE");
}catch(IllegalStateException ex){
}
try{
out.Bits(JBBPNumberOfBits.BITS_3, 12);
fail("Must throw ISE");
}catch(IllegalStateException ex){
}
try{
out.Bits(JBBPNumberOfBits.BITS_3, 12,13,14);
fail("Must throw ISE");
}catch(IllegalStateException ex){
}
try{
out.Bits(JBBPNumberOfBits.BITS_3, (byte)1,(byte)2,(byte)3);
fail("Must throw ISE");
}catch(IllegalStateException ex){
}
try{
out.Bool(true);
fail("Must throw ISE");
}catch(IllegalStateException ex){
}
try{
out.Bool(true,false);
fail("Must throw ISE");
}catch(IllegalStateException ex){
}
try{
out.Byte((byte)1,(byte)2,(byte)3);
fail("Must throw ISE");
}catch(IllegalStateException ex){
}
try{
out.Byte(1);
fail("Must throw ISE");
}catch(IllegalStateException ex){
}
try{
out.Byte(1,2,3);
fail("Must throw ISE");
}catch(IllegalStateException ex){
}
try{
out.ByteOrder(JBBPByteOrder.BIG_ENDIAN);
fail("Must throw ISE");
}catch(IllegalStateException ex){
}
try{
out.Flush();
fail("Must throw ISE");
}catch(IllegalStateException ex){
}
try{
out.Int(1);
fail("Must throw ISE");
}catch(IllegalStateException ex){
}
try{
out.Int(1,2);
fail("Must throw ISE");
}catch(IllegalStateException ex){
}
try{
out.Long(1L);
fail("Must throw ISE");
}catch(IllegalStateException ex){
}
try{
out.Long(1L,2L);
fail("Must throw ISE");
}catch(IllegalStateException ex){
}
try{
out.Short(1);
fail("Must throw ISE");
}catch(IllegalStateException ex){
}
try{
out.Short(1,2,3);
fail("Must throw ISE");
}catch(IllegalStateException ex){
}
try{
out.Short((short)1,(short)2,(short)3);
fail("Must throw ISE");
}catch(IllegalStateException ex){
}
try{
out.end();
fail("Must throw ISE");
}catch(IllegalStateException ex){
}
}
#location 9
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testBitArrayAsBytes() throws Exception {
assertArrayEquals(new byte[]{(byte) 0xE3}, BeginBin().Bit(new byte[]{(byte) 1, (byte) 3, (byte) 0, (byte) 2, (byte) 4, (byte) 1, (byte) 3, (byte) 7}).End().toByteArray());
assertArrayEquals(new byte[]{(byte) 0x0B}, BeginBin().Bit(new byte[]{(byte) 1, (byte) 3, (byte) 0, (byte) 7}).End().toByteArray());
} | #vulnerable code
@Test
public void testBitArrayAsBytes() throws Exception {
assertArrayEquals(new byte[]{(byte) 0xE3}, binStart().Bit(new byte[]{(byte) 1, (byte) 3, (byte) 0, (byte) 2, (byte) 4, (byte) 1, (byte) 3, (byte) 7}).end().toByteArray());
assertArrayEquals(new byte[]{(byte) 0x0B}, binStart().Bit(new byte[]{(byte) 1, (byte) 3, (byte) 0, (byte) 7}).end().toByteArray());
}
#location 4
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testAlign() throws Exception {
assertArrayEquals(new byte[]{(byte) 0x01, (byte) 0xFF}, JBBPOut.BeginBin().Bit(1).Align().Byte(0xFF).End().toByteArray());
} | #vulnerable code
@Test
public void testAlign() throws Exception {
assertArrayEquals(new byte[]{(byte) 0x01, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Bit(1).Align().Byte(0xFF).End().toByteArray());
}
#location 3
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testIntArray() throws Exception {
assertArrayEquals(new byte []{0x01,02,0x03,0x04,0x05,0x06,0x07,0x08}, BeginBin().Int(0x01020304, 0x05060708).End().toByteArray());
} | #vulnerable code
@Test
public void testIntArray() throws Exception {
assertArrayEquals(new byte []{0x01,02,0x03,0x04,0x05,0x06,0x07,0x08}, binStart().Int(0x01020304, 0x05060708).end().toByteArray());
}
#location 3
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testShortArray_AsShortArray() throws Exception {
assertArrayEquals(new byte[]{1, 2, 3, 4}, BeginBin().Short(new short[]{(short)0x0102, (short)0x0304}).End().toByteArray());
} | #vulnerable code
@Test
public void testShortArray_AsShortArray() throws Exception {
assertArrayEquals(new byte[]{1, 2, 3, 4}, binStart().Short(new short[]{(short)0x0102, (short)0x0304}).end().toByteArray());
}
#location 3
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testGetLineSeparator() throws Exception {
assertEquals("hello", new JBBPTextWriter(writer, JBBPByteOrder.BIG_ENDIAN, "hello", 11, "", "", "","", "").getLineSeparator());
} | #vulnerable code
@Test
public void testGetLineSeparator() throws Exception {
assertEquals("hello", new JBBPTextWriter(writer, JBBPByteOrder.BIG_ENDIAN, "hello", 11, "", "", "", "").getLineSeparator());
}
#location 3
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testShort() throws Exception {
assertArrayEquals(new byte []{0x01,02}, BeginBin().Short(0x0102).End().toByteArray());
} | #vulnerable code
@Test
public void testShort() throws Exception {
assertArrayEquals(new byte []{0x01,02}, binStart().Short(0x0102).end().toByteArray());
}
#location 3
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testBits_Int() throws Exception {
assertArrayEquals(new byte[]{0xD}, BeginBin().Bits(JBBPNumberOfBits.BITS_4, 0xFD).End().toByteArray());
} | #vulnerable code
@Test
public void testBits_Int() throws Exception {
assertArrayEquals(new byte[]{0xD}, binStart().Bits(JBBPNumberOfBits.BITS_4, 0xFD).end().toByteArray());
}
#location 3
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testEmptyArray() throws Exception {
assertEquals(0, JBBPOut.BeginBin().End().toByteArray().length);
} | #vulnerable code
@Test
public void testEmptyArray() throws Exception {
assertEquals(0, new JBBPOut(new ByteArrayOutputStream()).End().toByteArray().length);
}
#location 3
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testShortArray_AsIntegers_LittleEndian() throws Exception {
assertArrayEquals(new byte []{2,1,4,3}, BeginBin().ByteOrder(JBBPByteOrder.LITTLE_ENDIAN).Short(0x0102,0x0304).End().toByteArray());
} | #vulnerable code
@Test
public void testShortArray_AsIntegers_LittleEndian() throws Exception {
assertArrayEquals(new byte []{2,1,4,3}, binStart().ByteOrder(JBBPByteOrder.LITTLE_ENDIAN).Short(0x0102,0x0304).end().toByteArray());
}
#location 3
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public byte[] readByteArray(final int items) throws IOException {
return _readArray(items, null);
} | #vulnerable code
public byte[] readByteArray(final int items) throws IOException {
int pos = 0;
if (items < 0) {
byte[] buffer = new byte[INITIAL_ARRAY_BUFFER_SIZE];
// till end
while (true) {
final int next = read();
if (next < 0) {
break;
}
if (buffer.length == pos) {
final byte[] newbuffer = new byte[buffer.length << 1];
System.arraycopy(buffer, 0, newbuffer, 0, buffer.length);
buffer = newbuffer;
}
buffer[pos++] = (byte) next;
}
if (buffer.length == pos) {
return buffer;
}
final byte[] result = new byte[pos];
System.arraycopy(buffer, 0, result, 0, pos);
return result;
}
else {
// number
final byte[] buffer = new byte[items];
final int read = this.read(buffer, 0, items);
if (read != items) {
throw new EOFException("Have read only " + read + " byte(s) instead of " + items + " byte(s)");
}
return buffer;
}
}
#location 7
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testBitArrayAsBooleans() throws Exception {
assertArrayEquals(new byte[]{(byte) 0xE3}, BeginBin().Bit(true, true, false, false, false, true, true, true).End().toByteArray());
assertArrayEquals(new byte[]{(byte) 0x0B}, BeginBin().Bit(true, true, false, true).End().toByteArray());
} | #vulnerable code
@Test
public void testBitArrayAsBooleans() throws Exception {
assertArrayEquals(new byte[]{(byte) 0xE3}, binStart().Bit(true, true, false, false, false, true, true, true).end().toByteArray());
assertArrayEquals(new byte[]{(byte) 0x0B}, binStart().Bit(true, true, false, true).end().toByteArray());
}
#location 3
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testLongArray() throws Exception {
assertArrayEquals(new byte []{0x01,02,0x03,0x04,0x05,0x06,0x07,0x08, 0x11,0x12,0x13,0x14,0x15,0x16,0x17,0x18}, BeginBin().Long(0x0102030405060708L,0x1112131415161718L).End().toByteArray());
} | #vulnerable code
@Test
public void testLongArray() throws Exception {
assertArrayEquals(new byte []{0x01,02,0x03,0x04,0x05,0x06,0x07,0x08, 0x11,0x12,0x13,0x14,0x15,0x16,0x17,0x18}, binStart().Long(0x0102030405060708L,0x1112131415161718L).end().toByteArray());
}
#location 3
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testBeginBin() throws Exception {
assertArrayEquals(new byte[]{1}, BeginBin().Byte(1).End().toByteArray());
assertArrayEquals(new byte[]{0x02, 0x01}, BeginBin(JBBPByteOrder.LITTLE_ENDIAN).Short(0x0102).End().toByteArray());
assertArrayEquals(new byte[]{0x40, (byte) 0x80}, BeginBin(JBBPByteOrder.LITTLE_ENDIAN, JBBPBitOrder.MSB0).Short(0x0102).End().toByteArray());
assertArrayEquals(new byte[]{(byte) 0x80}, BeginBin(JBBPBitOrder.MSB0).Byte(1).End().toByteArray());
assertArrayEquals(new byte[]{(byte) 0x80}, BeginBin(1).Byte(0x80).End().toByteArray());
final ByteArrayOutputStream buffer1 = new ByteArrayOutputStream();
assertSame(buffer1, BeginBin(buffer1).End());
final ByteArrayOutputStream buffer2 = new ByteArrayOutputStream();
BeginBin(buffer2,JBBPByteOrder.LITTLE_ENDIAN, JBBPBitOrder.MSB0).Short(1234).End();
assertArrayEquals(new byte[]{(byte)0x4b, (byte)0x20}, buffer2.toByteArray());
} | #vulnerable code
@Test
public void testBeginBin() throws Exception {
assertArrayEquals(new byte[]{1}, BeginBin().Byte(1).End().toByteArray());
assertArrayEquals(new byte[]{0x02, 0x01}, BeginBin(JBBPByteOrder.LITTLE_ENDIAN).Short(0x0102).End().toByteArray());
assertArrayEquals(new byte[]{0x40, (byte) 0x80}, BeginBin(JBBPByteOrder.LITTLE_ENDIAN, JBBPBitOrder.MSB0).Short(0x0102).End().toByteArray());
assertArrayEquals(new byte[]{(byte) 0x80}, BeginBin(JBBPBitOrder.MSB0).Byte(1).End().toByteArray());
assertArrayEquals(new byte[]{(byte) 0x80}, BeginBin(1).Byte(0x80).End().toByteArray());
final ByteArrayOutputStream buffer = new ByteArrayOutputStream();
assertSame(buffer, BeginBin(buffer).End());
}
#location 10
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testShort_BigEndian() throws Exception {
assertArrayEquals(new byte []{0x01,02}, BeginBin().ByteOrder(JBBPByteOrder.BIG_ENDIAN).Short(0x0102).End().toByteArray());
} | #vulnerable code
@Test
public void testShort_BigEndian() throws Exception {
assertArrayEquals(new byte []{0x01,02}, binStart().ByteOrder(JBBPByteOrder.BIG_ENDIAN).Short(0x0102).end().toByteArray());
}
#location 3
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testBits_ByteArray() throws Exception {
assertArrayEquals(new byte[]{(byte) 0xED}, BeginBin().Bits(JBBPNumberOfBits.BITS_4, (byte) 0xFD, (byte) 0x8E).End().toByteArray());
} | #vulnerable code
@Test
public void testBits_ByteArray() throws Exception {
assertArrayEquals(new byte[]{(byte) 0xED}, binStart().Bits(JBBPNumberOfBits.BITS_4, (byte) 0xFD, (byte) 0x8E).end().toByteArray());
}
#location 3
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testLong_BigEndian() throws Exception {
assertArrayEquals(new byte []{0x01, 02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}, BeginBin().ByteOrder(JBBPByteOrder.BIG_ENDIAN).Long(0x0102030405060708L).End().toByteArray());
} | #vulnerable code
@Test
public void testLong_BigEndian() throws Exception {
assertArrayEquals(new byte []{0x01, 02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}, binStart().ByteOrder(JBBPByteOrder.BIG_ENDIAN).Long(0x0102030405060708L).end().toByteArray());
}
#location 3
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public byte[] readBitsArray(final int items, final JBBPBitNumber bitNumber) throws IOException {
return _readArray(items, bitNumber);
} | #vulnerable code
public byte[] readBitsArray(final int items, final JBBPBitNumber bitNumber) throws IOException {
int pos = 0;
if (items < 0) {
byte[] buffer = new byte[INITIAL_ARRAY_BUFFER_SIZE];
// till end
while (true) {
final int next = readBits(bitNumber);
if (next < 0) {
break;
}
if (buffer.length == pos) {
final byte[] newbuffer = new byte[buffer.length << 1];
System.arraycopy(buffer, 0, newbuffer, 0, buffer.length);
buffer = newbuffer;
}
buffer[pos++] = (byte) next;
}
if (buffer.length == pos) {
return buffer;
}
final byte[] result = new byte[pos];
System.arraycopy(buffer, 0, result, 0, pos);
return result;
}
else {
// number
final byte[] buffer = new byte[items];
for (int i = 0; i < items; i++) {
final int next = readBits(bitNumber);
if (next < 0) {
throw new EOFException("Have read only " + i + " bit portions instead of " + items);
}
buffer[i] = (byte) next;
}
return buffer;
}
}
#location 7
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testInt_BigEndian() throws Exception {
assertArrayEquals(new byte []{0x01,0x02,0x03,0x04}, BeginBin().ByteOrder(JBBPByteOrder.BIG_ENDIAN).Int(0x01020304).End().toByteArray());
} | #vulnerable code
@Test
public void testInt_BigEndian() throws Exception {
assertArrayEquals(new byte []{0x01,0x02,0x03,0x04}, binStart().ByteOrder(JBBPByteOrder.BIG_ENDIAN).Int(0x01020304).end().toByteArray());
}
#location 3
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testComplexWriting_1() throws Exception {
final byte [] array =
BeginBin().
Bit(1, 2, 3, 0).
Bit(true, false, true).
Align().
Byte(5).
Short(1, 2, 3, 4, 5).
Bool(true, false, true, true).
Int(0xABCDEF23, 0xCAFEBABE).
Long(0x123456789ABCDEF1L, 0x212356239091AB32L).
End().toByteArray();
assertEquals(40, array.length);
assertArrayEquals(new byte[]{
(byte) 0x55, 5, 0, 1, 0, 2, 0, 3, 0, 4, 0, 5, 1, 0, 1, 1,
(byte) 0xAB, (byte) 0xCD, (byte) 0xEF, 0x23, (byte) 0xCA, (byte) 0xFE, (byte) 0xBA, (byte) 0xBE,
0x12, 0x34, 0x56, 0x78, (byte) 0x9A, (byte) 0xBC, (byte) 0xDE, (byte) 0xF1, 0x21, 0x23, 0x56, 0x23, (byte) 0x90, (byte) 0x91, (byte) 0xAB, 0x32
}, array);
} | #vulnerable code
@Test
public void testComplexWriting_1() throws Exception {
final ByteArrayOutputStream buffer = new ByteArrayOutputStream(16384);
final JBBPOut begin = new JBBPOut(buffer);
begin.
Bit(1, 2, 3, 0).
Bit(true, false, true).
Align().
Byte(5).
Short(1, 2, 3, 4, 5).
Bool(true, false, true, true).
Int(0xABCDEF23, 0xCAFEBABE).
Long(0x123456789ABCDEF1L, 0x212356239091AB32L).
end();
final byte[] array = buffer.toByteArray();
assertEquals(40, array.length);
assertArrayEquals(new byte[]{
(byte) 0x55, 5, 0, 1, 0, 2, 0, 3, 0, 4, 0, 5, 1, 0, 1, 1,
(byte) 0xAB, (byte) 0xCD, (byte) 0xEF, 0x23, (byte) 0xCA, (byte) 0xFE, (byte) 0xBA, (byte) 0xBE,
0x12, 0x34, 0x56, 0x78, (byte) 0x9A, (byte) 0xBC, (byte) 0xDE, (byte) 0xF1, 0x21, 0x23, 0x56, 0x23, (byte) 0x90, (byte) 0x91, (byte) 0xAB, 0x32
}, array);
}
#location 11
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testBit_LSB0() throws Exception {
assertArrayEquals(new byte[]{(byte) 0x01}, BeginBin(JBBPByteOrder.BIG_ENDIAN, JBBPBitOrder.LSB0).Bit(1).End().toByteArray());
} | #vulnerable code
@Test
public void testBit_LSB0() throws Exception {
assertArrayEquals(new byte[]{(byte) 0x01}, binStart(JBBPByteOrder.BIG_ENDIAN, JBBPBitOrder.LSB0).Bit(1).end().toByteArray());
}
#location 3
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testShortArray_AsIntegers_BigEndian() throws Exception {
assertArrayEquals(new byte []{1,2,3,4}, BeginBin().ByteOrder(JBBPByteOrder.BIG_ENDIAN).Short(0x0102,0x0304).End().toByteArray());
} | #vulnerable code
@Test
public void testShortArray_AsIntegers_BigEndian() throws Exception {
assertArrayEquals(new byte []{1,2,3,4}, binStart().ByteOrder(JBBPByteOrder.BIG_ENDIAN).Short(0x0102,0x0304).end().toByteArray());
}
#location 3
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testBitArrayAsBooleans() throws Exception {
assertArrayEquals(new byte[]{(byte) 0xE3}, BeginBin().Bit(true, true, false, false, false, true, true, true).End().toByteArray());
assertArrayEquals(new byte[]{(byte) 0x0B}, BeginBin().Bit(true, true, false, true).End().toByteArray());
} | #vulnerable code
@Test
public void testBitArrayAsBooleans() throws Exception {
assertArrayEquals(new byte[]{(byte) 0xE3}, binStart().Bit(true, true, false, false, false, true, true, true).end().toByteArray());
assertArrayEquals(new byte[]{(byte) 0x0B}, binStart().Bit(true, true, false, true).end().toByteArray());
}
#location 4
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testBits_IntArray() throws Exception {
assertArrayEquals(new byte[]{(byte) 0xED}, BeginBin().Bits(JBBPNumberOfBits.BITS_4, 0xFD, 0xFE).End().toByteArray());
} | #vulnerable code
@Test
public void testBits_IntArray() throws Exception {
assertArrayEquals(new byte[]{(byte) 0xED}, binStart().Bits(JBBPNumberOfBits.BITS_4, 0xFD, 0xFE).end().toByteArray());
}
#location 3
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testParse_StructArray_IgnoredForZeroLength() throws Exception {
final JBBPFieldStruct parsed = JBBPParser.prepare("byte len; sss [len] { byte a; byte b; byte c;} ushort;").parse(new byte[]{0x0, 0x01, (byte) 0x02});
assertEquals(0,parsed.findFieldForType(JBBPFieldArrayStruct.class).size());
assertEquals(0x0102, parsed.findFieldForType(JBBPFieldUShort.class).getAsInt());
} | #vulnerable code
@Test
public void testParse_StructArray_IgnoredForZeroLength() throws Exception {
final JBBPFieldStruct parsed = JBBPParser.prepare("byte len; sss [len] { byte a; byte b; byte c;} ushort;").parse(new byte[]{0x0, 0x01, (byte) 0x02});
assertNull(parsed.findFieldForType(JBBPFieldArrayStruct.class));
assertEquals(0x0102, parsed.findFieldForType(JBBPFieldUShort.class).getAsInt());
}
#location 5
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private byte[] callWrite(final Object instance) throws Exception {
final ByteArrayOutputStream bout = new ByteArrayOutputStream();
final JBBPBitOutputStream bitout = new JBBPBitOutputStream(bout);
instance.getClass().getMethod("write", JBBPBitOutputStream.class).invoke(instance, bitout);
bitout.close();
return bout.toByteArray();
} | #vulnerable code
private byte[] callWrite(final Object instance) throws Exception {
final ByteArrayOutputStream bout = new ByteArrayOutputStream();
instance.getClass().getMethod("write", JBBPBitOutputStream.class).invoke(instance, new JBBPBitOutputStream(bout));
bout.close();
return bout.toByteArray();
}
#location 3
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public int readBits(final JBBPBitNumber numOfBitsToRead) throws IOException {
int result;
final int numOfBitsAsNumber = numOfBitsToRead.getBitNumber();
if (this.bitsInBuffer == 0 && numOfBitsAsNumber == 8) {
result = this.readByteFromStream();
this.byteCounter++;
return result;
}
else {
result = 0;
if (numOfBitsAsNumber == this.bitsInBuffer) {
result = this.bitBuffer;
this.bitBuffer = 0;
this.bitsInBuffer = 0;
if (numOfBitsAsNumber == 8) {
this.byteCounter++;
}
return result;
}
int i = numOfBitsAsNumber;
int theBitBuffer = this.bitBuffer;
int theBitBufferCounter = this.bitsInBuffer;
while (i > 0) {
if (theBitBufferCounter == 0) {
final int nextByte = this.readByteFromStream();
if (nextByte < 0) {
if (i == numOfBitsAsNumber) {
return nextByte;
}
else {
break;
}
}
else {
theBitBuffer = nextByte;
theBitBufferCounter = 8;
this.byteCounter++;
}
}
result = (result << 1) | (theBitBuffer & 1);
theBitBuffer >>= 1;
theBitBufferCounter--;
i--;
}
this.bitBuffer = theBitBuffer;
this.bitsInBuffer = theBitBufferCounter;
return (JBBPUtils.reverseByte((byte) result) & 0xFF) >> (8 - (numOfBitsAsNumber - i));
}
} | #vulnerable code
public int readBits(final JBBPBitNumber numOfBitsToRead) throws IOException {
int result;
final int numOfBitsAsNumber = numOfBitsToRead.getBitNumber();
if (this.bitsInBuffer == 0 && numOfBitsAsNumber == 8) {
result = this.readByteFromStream();
return result;
}
else {
result = 0;
if (numOfBitsAsNumber == this.bitsInBuffer){
result = this.bitBuffer;
this.bitBuffer = 0;
this.bitsInBuffer = 0;
return result;
}
int i = numOfBitsAsNumber;
int theBitBuffer = this.bitBuffer;
int theBitBufferCounter = this.bitsInBuffer;
while (i > 0) {
if (theBitBufferCounter == 0) {
final int nextByte = this.readByteFromStream();
if (nextByte < 0) {
if (i == numOfBitsAsNumber) {
return nextByte;
}
else {
break;
}
}
else {
theBitBuffer = nextByte;
theBitBufferCounter = 8;
}
}
result = (result << 1) | (theBitBuffer & 1);
theBitBuffer >>= 1;
theBitBufferCounter--;
i--;
}
this.bitBuffer = theBitBuffer;
this.bitsInBuffer = theBitBufferCounter;
return (JBBPUtils.reverseByte((byte) result) & 0xFF) >> (8 - (numOfBitsAsNumber - i));
}
}
#location 7
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testAlignWithArgument() throws Exception {
assertEquals(0, JBBPOut.BeginBin().Align(2).End().toByteArray().length);
assertArrayEquals(new byte[]{(byte) 0x01, (byte) 0xFF}, JBBPOut.BeginBin().Bit(1).Align(1).Byte(0xFF).End().toByteArray());
assertArrayEquals(new byte[]{(byte) 0xFF}, JBBPOut.BeginBin().Align(3).Byte(0xFF).End().toByteArray());
assertArrayEquals(new byte[]{0x01, (byte) 0xFF}, JBBPOut.BeginBin().Bit(1).Align(1).Byte(0xFF).End().toByteArray());
assertArrayEquals(new byte[]{0x01, 0x00, (byte) 0xFF}, JBBPOut.BeginBin().Bit(1).Align(2).Byte(0xFF).End().toByteArray());
assertArrayEquals(new byte[]{0x01, 0x00, 0x00, 0x00, (byte) 0xFF}, JBBPOut.BeginBin().Bit(1).Align(4).Byte(0xFF).End().toByteArray());
assertArrayEquals(new byte[]{0x01, 0x02, 0x00, 0x00, (byte) 0xFF}, JBBPOut.BeginBin().Byte(1, 2).Align(4).Byte(0xFF).End().toByteArray());
assertArrayEquals(new byte[]{0x01, 0x02, 0x03, 0x00, 0x00, (byte) 0xFF}, JBBPOut.BeginBin().Byte(1, 2, 3).Align(5).Byte(0xFF).End().toByteArray());
assertArrayEquals(new byte[]{0x01, 0x02, 0x03, 0x04, 0x00, (byte) 0xFF}, JBBPOut.BeginBin().Byte(1, 2, 3, 4).Align(5).Byte(0xFF).End().toByteArray());
assertArrayEquals(new byte[]{0x01, 0x02, 0x03, 0x04, 0x05, (byte) 0xFF}, JBBPOut.BeginBin().Byte(1, 2, 3, 4, 5).Align(5).Byte(0xFF).End().toByteArray());
assertArrayEquals(new byte[]{(byte) 0x01, 0x00, 0x02, 0x00, (byte) 0x03}, JBBPOut.BeginBin().Align(2).Byte(1).Align(2).Byte(2).Align(2).Byte(3).End().toByteArray());
assertArrayEquals(new byte[]{(byte) 0xF1, 0x00, (byte) 0x01, 0x00, 0x02, 0x00, (byte) 0x03}, JBBPOut.BeginBin().Byte(0xF1).Align(2).Byte(1).Align(2).Byte(2).Align(2).Byte(3).End().toByteArray());
assertArrayEquals(new byte[]{(byte) 0xF1, 0x00, 0x00, (byte) 0x01, 0x00, 00, 0x02, 0x00, 00, (byte) 0x03}, JBBPOut.BeginBin().Byte(0xF1).Align(3).Byte(1).Align(3).Byte(2).Align(3).Byte(3).End().toByteArray());
assertArrayEquals(new byte[]{0x01, 0x02, 03, 0x04, 0x00, (byte)0xF1}, JBBPOut.BeginBin().Int(0x01020304).Align(5).Byte(0xF1).End().toByteArray());
assertArrayEquals(new byte[]{0x01, 0x00, 0x00, 0x00, 0x00, (byte)0xF1}, JBBPOut.BeginBin().Bit(1).Align(5).Byte(0xF1).End().toByteArray());
} | #vulnerable code
@Test
public void testAlignWithArgument() throws Exception {
assertEquals(0, new JBBPOut(new ByteArrayOutputStream()).Align(2).End().toByteArray().length);
assertArrayEquals(new byte[]{(byte) 0x01, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Bit(1).Align(1).Byte(0xFF).End().toByteArray());
assertArrayEquals(new byte[]{(byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Align(3).Byte(0xFF).End().toByteArray());
assertArrayEquals(new byte[]{0x01, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Bit(1).Align(1).Byte(0xFF).End().toByteArray());
assertArrayEquals(new byte[]{0x01, 0x00, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Bit(1).Align(2).Byte(0xFF).End().toByteArray());
assertArrayEquals(new byte[]{0x01, 0x00, 0x00, 0x00, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Bit(1).Align(4).Byte(0xFF).End().toByteArray());
assertArrayEquals(new byte[]{0x01, 0x02, 0x00, 0x00, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Byte(1, 2).Align(4).Byte(0xFF).End().toByteArray());
assertArrayEquals(new byte[]{0x01, 0x02, 0x03, 0x00, 0x00, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Byte(1, 2, 3).Align(5).Byte(0xFF).End().toByteArray());
assertArrayEquals(new byte[]{0x01, 0x02, 0x03, 0x04, 0x00, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Byte(1, 2, 3, 4).Align(5).Byte(0xFF).End().toByteArray());
assertArrayEquals(new byte[]{0x01, 0x02, 0x03, 0x04, 0x05, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Byte(1, 2, 3, 4, 5).Align(5).Byte(0xFF).End().toByteArray());
assertArrayEquals(new byte[]{(byte) 0x01, 0x00, 0x02, 0x00, (byte) 0x03}, new JBBPOut(new ByteArrayOutputStream()).Align(2).Byte(1).Align(2).Byte(2).Align(2).Byte(3).End().toByteArray());
assertArrayEquals(new byte[]{(byte) 0xF1, 0x00, (byte) 0x01, 0x00, 0x02, 0x00, (byte) 0x03}, new JBBPOut(new ByteArrayOutputStream()).Byte(0xF1).Align(2).Byte(1).Align(2).Byte(2).Align(2).Byte(3).End().toByteArray());
assertArrayEquals(new byte[]{(byte) 0xF1, 0x00, 0x00, (byte) 0x01, 0x00, 00, 0x02, 0x00, 00, (byte) 0x03}, new JBBPOut(new ByteArrayOutputStream()).Byte(0xF1).Align(3).Byte(1).Align(3).Byte(2).Align(3).Byte(3).End().toByteArray());
assertArrayEquals(new byte[]{0x01, 0x02, 03, 0x04, 0x00, (byte)0xF1}, new JBBPOut(new ByteArrayOutputStream()).Int(0x01020304).Align(5).Byte(0xF1).End().toByteArray());
assertArrayEquals(new byte[]{0x01, 0x00, 0x00, 0x00, 0x00, (byte)0xF1}, new JBBPOut(new ByteArrayOutputStream()).Bit(1).Align(5).Byte(0xF1).End().toByteArray());
}
#location 4
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testShortArray_AsIntegers() throws Exception {
assertArrayEquals(new byte []{1,2,3,4}, BeginBin().Short(0x0102,0x0304).End().toByteArray());
} | #vulnerable code
@Test
public void testShortArray_AsIntegers() throws Exception {
assertArrayEquals(new byte []{1,2,3,4}, binStart().Short(0x0102,0x0304).end().toByteArray());
}
#location 3
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testInt() throws Exception {
assertArrayEquals(new byte []{0x01,02,0x03,0x04}, BeginBin().Int(0x01020304).End().toByteArray());
} | #vulnerable code
@Test
public void testInt() throws Exception {
assertArrayEquals(new byte []{0x01,02,0x03,0x04}, binStart().Int(0x01020304).end().toByteArray());
}
#location 3
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testByteArrayAsInts() throws Exception {
assertArrayEquals(new byte[]{1, 3, 0, 2, 4, 1, 3, 7}, BeginBin().Byte(1, 3, 0, 2, 4, 1, 3, 7).End().toByteArray());
} | #vulnerable code
@Test
public void testByteArrayAsInts() throws Exception {
assertArrayEquals(new byte[]{1, 3, 0, 2, 4, 1, 3, 7}, binStart().Byte(1, 3, 0, 2, 4, 1, 3, 7).end().toByteArray());
}
#location 3
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testLong() throws Exception {
assertArrayEquals(new byte []{0x01,02,0x03,0x04,0x05,0x06,0x07,0x08}, BeginBin().Long(0x0102030405060708L).End().toByteArray());
} | #vulnerable code
@Test
public void testLong() throws Exception {
assertArrayEquals(new byte []{0x01,02,0x03,0x04,0x05,0x06,0x07,0x08}, binStart().Long(0x0102030405060708L).end().toByteArray());
}
#location 3
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testComplexWriting_1() throws Exception {
final byte [] array =
BeginBin().
Bit(1, 2, 3, 0).
Bit(true, false, true).
Align().
Byte(5).
Short(1, 2, 3, 4, 5).
Bool(true, false, true, true).
Int(0xABCDEF23, 0xCAFEBABE).
Long(0x123456789ABCDEF1L, 0x212356239091AB32L).
End().toByteArray();
assertEquals(40, array.length);
assertArrayEquals(new byte[]{
(byte) 0x55, 5, 0, 1, 0, 2, 0, 3, 0, 4, 0, 5, 1, 0, 1, 1,
(byte) 0xAB, (byte) 0xCD, (byte) 0xEF, 0x23, (byte) 0xCA, (byte) 0xFE, (byte) 0xBA, (byte) 0xBE,
0x12, 0x34, 0x56, 0x78, (byte) 0x9A, (byte) 0xBC, (byte) 0xDE, (byte) 0xF1, 0x21, 0x23, 0x56, 0x23, (byte) 0x90, (byte) 0x91, (byte) 0xAB, 0x32
}, array);
} | #vulnerable code
@Test
public void testComplexWriting_1() throws Exception {
final ByteArrayOutputStream buffer = new ByteArrayOutputStream(16384);
final JBBPOut begin = new JBBPOut(buffer);
begin.
Bit(1, 2, 3, 0).
Bit(true, false, true).
Align().
Byte(5).
Short(1, 2, 3, 4, 5).
Bool(true, false, true, true).
Int(0xABCDEF23, 0xCAFEBABE).
Long(0x123456789ABCDEF1L, 0x212356239091AB32L).
end();
final byte[] array = buffer.toByteArray();
assertEquals(40, array.length);
assertArrayEquals(new byte[]{
(byte) 0x55, 5, 0, 1, 0, 2, 0, 3, 0, 4, 0, 5, 1, 0, 1, 1,
(byte) 0xAB, (byte) 0xCD, (byte) 0xEF, 0x23, (byte) 0xCA, (byte) 0xFE, (byte) 0xBA, (byte) 0xBE,
0x12, 0x34, 0x56, 0x78, (byte) 0x9A, (byte) 0xBC, (byte) 0xDE, (byte) 0xF1, 0x21, 0x23, 0x56, 0x23, (byte) 0x90, (byte) 0x91, (byte) 0xAB, 0x32
}, array);
}
#location 5
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public BigDecimal convert(Currency from, Currency to, BigDecimal amount) {
Assert.notNull(amount);
Map<Currency, BigDecimal> rates = getCurrentRates();
BigDecimal ratio = rates.get(to).divide(rates.get(from), 4, RoundingMode.HALF_UP);
return amount.multiply(ratio);
} | #vulnerable code
@Override
public BigDecimal convert(Currency from, Currency to, BigDecimal amount) {
Map<Currency, BigDecimal> rates = getCurrentRates();
BigDecimal baseRatio = rates.get(to).divide(rates.get(from), 4, RoundingMode.HALF_UP);
return amount.multiply(baseRatio);
}
#location 5
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void debugLocal() {
if (!traceDebugEnabled) {
return;
}
System.out.println("---------------- Trace Information ---------------");
String traceId = getTraceId();
String spanId = getSpanId();
System.out.println(DiscoveryConstant.TRACE_ID + "=" + (StringUtils.isNotEmpty(traceId) ? traceId : StringUtils.EMPTY));
System.out.println(DiscoveryConstant.SPAN_ID + "=" + (StringUtils.isNotEmpty(spanId) ? spanId : StringUtils.EMPTY));
System.out.println(DiscoveryConstant.N_D_SERVICE_GROUP + "=" + pluginAdapter.getGroup());
System.out.println(DiscoveryConstant.N_D_SERVICE_TYPE + "=" + pluginAdapter.getServiceType());
System.out.println(DiscoveryConstant.N_D_SERVICE_ID + "=" + pluginAdapter.getServiceId());
System.out.println(DiscoveryConstant.N_D_SERVICE_ADDRESS + "=" + pluginAdapter.getHost() + ":" + pluginAdapter.getPort());
System.out.println(DiscoveryConstant.N_D_SERVICE_VERSION + "=" + pluginAdapter.getVersion());
System.out.println(DiscoveryConstant.N_D_SERVICE_REGION + "=" + pluginAdapter.getRegion());
System.out.println(DiscoveryConstant.N_D_SERVICE_ENVIRONMENT + "=" + pluginAdapter.getEnvironment());
String routeVersion = strategyContextHolder.getHeader(DiscoveryConstant.N_D_VERSION);
if (StringUtils.isNotEmpty(routeVersion)) {
System.out.println(DiscoveryConstant.N_D_VERSION + "=" + routeVersion);
}
String routeRegion = strategyContextHolder.getHeader(DiscoveryConstant.N_D_REGION);
if (StringUtils.isNotEmpty(routeRegion)) {
System.out.println(DiscoveryConstant.N_D_REGION + "=" + routeRegion);
}
String routeAddress = strategyContextHolder.getHeader(DiscoveryConstant.N_D_ADDRESS);
if (StringUtils.isNotEmpty(routeAddress)) {
System.out.println(DiscoveryConstant.N_D_ADDRESS + "=" + routeAddress);
}
String routeVersionWeight = strategyContextHolder.getHeader(DiscoveryConstant.N_D_VERSION_WEIGHT);
if (StringUtils.isNotEmpty(routeVersionWeight)) {
System.out.println(DiscoveryConstant.N_D_VERSION_WEIGHT + "=" + routeVersionWeight);
}
String routeRegionWeight = strategyContextHolder.getHeader(DiscoveryConstant.N_D_REGION_WEIGHT);
if (StringUtils.isNotEmpty(routeRegionWeight)) {
System.out.println(DiscoveryConstant.N_D_REGION_WEIGHT + "=" + routeRegionWeight);
}
Map<String, String> customizationMap = getCustomizationMap();
if (MapUtils.isNotEmpty(customizationMap)) {
for (Map.Entry<String, String> entry : customizationMap.entrySet()) {
System.out.println(entry.getKey() + "=" + entry.getValue());
}
}
System.out.println("--------------------------------------------------");
} | #vulnerable code
public void debugLocal() {
if (!traceDebugEnabled) {
return;
}
System.out.println("---------------- Trace Information ---------------");
String traceId = getTraceId();
String spanId = getSpanId();
System.out.println(DiscoveryConstant.TRACE_ID + "=" + (StringUtils.isNotEmpty(traceId) ? traceId : StringUtils.EMPTY));
System.out.println(DiscoveryConstant.SPAN_ID + "=" + (StringUtils.isNotEmpty(spanId) ? spanId : StringUtils.EMPTY));
System.out.println(DiscoveryConstant.N_D_SERVICE_GROUP + "=" + pluginAdapter.getGroup());
System.out.println(DiscoveryConstant.N_D_SERVICE_TYPE + "=" + pluginAdapter.getServiceType());
System.out.println(DiscoveryConstant.N_D_SERVICE_ID + "=" + pluginAdapter.getServiceId());
System.out.println(DiscoveryConstant.N_D_SERVICE_ADDRESS + "=" + pluginAdapter.getHost() + ":" + pluginAdapter.getPort());
System.out.println(DiscoveryConstant.N_D_SERVICE_VERSION + "=" + pluginAdapter.getVersion());
System.out.println(DiscoveryConstant.N_D_SERVICE_REGION + "=" + pluginAdapter.getRegion());
String routeVersion = strategyContextHolder.getHeader(DiscoveryConstant.N_D_VERSION);
if (StringUtils.isNotEmpty(routeVersion)) {
System.out.println(DiscoveryConstant.N_D_VERSION + "=" + routeVersion);
}
String routeRegion = strategyContextHolder.getHeader(DiscoveryConstant.N_D_REGION);
if (StringUtils.isNotEmpty(routeRegion)) {
System.out.println(DiscoveryConstant.N_D_REGION + "=" + routeRegion);
}
String routeAddress = strategyContextHolder.getHeader(DiscoveryConstant.N_D_ADDRESS);
if (StringUtils.isNotEmpty(routeAddress)) {
System.out.println(DiscoveryConstant.N_D_ADDRESS + "=" + routeAddress);
}
String routeVersionWeight = strategyContextHolder.getHeader(DiscoveryConstant.N_D_VERSION_WEIGHT);
if (StringUtils.isNotEmpty(routeVersionWeight)) {
System.out.println(DiscoveryConstant.N_D_VERSION_WEIGHT + "=" + routeVersionWeight);
}
String routeRegionWeight = strategyContextHolder.getHeader(DiscoveryConstant.N_D_REGION_WEIGHT);
if (StringUtils.isNotEmpty(routeRegionWeight)) {
System.out.println(DiscoveryConstant.N_D_REGION_WEIGHT + "=" + routeRegionWeight);
}
Map<String, String> customizationMap = getCustomizationMap();
if (MapUtils.isNotEmpty(customizationMap)) {
for (Map.Entry<String, String> entry : customizationMap.entrySet()) {
System.out.println(entry.getKey() + "=" + entry.getValue());
}
}
System.out.println("--------------------------------------------------");
}
#location 41
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public boolean apply(Server server, Map<String, String> metadata) {
// 1.对Rest调用传来的Header的路由Version做策略。注意这个Version不是灰度发布的Version
boolean enabled = super.apply(server, metadata);
if (!enabled) {
return false;
}
// 2.对Rest调用传来的Header参数(例如Token)做策略
return applyFromHeader(server, metadata);
} | #vulnerable code
@Override
public boolean apply(Server server, Map<String, String> metadata) {
GatewayStrategyContext context = GatewayStrategyContext.getCurrentContext();
String token = context.getExchange().getRequest().getHeaders().getFirst("token");
// String value = context.getExchange().getRequest().getQueryParams().getFirst("value");
// 执行完后,请手工清除上下文对象,否则可能会造成内存泄露
GatewayStrategyContext.clearCurrentContext();
String serviceId = server.getMetaInfo().getAppName().toLowerCase();
LOG.info("Gateway端负载均衡用户定制触发:serviceId={}, host={}, metadata={}, context={}", serviceId, server.toString(), metadata, context);
String filterToken = "abc";
if (StringUtils.isNotEmpty(token) && token.contains(filterToken)) {
LOG.info("过滤条件:当Token含有'{}'的时候,不能被Ribbon负载均衡到", filterToken);
return false;
}
return true;
}
#location 15
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public Server choose(Object key) {
WeightFilterEntity weightFilterEntity = weightRandomLoadBalance.getWeightFilterEntity();
if (weightFilterEntity == null) {
return super.choose(key);
}
if (!weightFilterEntity.hasWeight()) {
return super.choose(key);
}
List<Server> eligibleServers = getPredicate().getEligibleServers(getLoadBalancer().getAllServers(), key);
try {
return weightRandomLoadBalance.choose(eligibleServers, weightFilterEntity);
} catch (Exception e) {
return super.choose(key);
}
} | #vulnerable code
@Override
public Server choose(Object key) {
WeightFilterEntity weightFilterEntity = weightRandomLoadBalance.getWeightFilterEntity();
if (!weightFilterEntity.hasWeight()) {
return super.choose(key);
}
List<Server> eligibleServers = getPredicate().getEligibleServers(getLoadBalancer().getAllServers(), key);
try {
return weightRandomLoadBalance.choose(eligibleServers, weightFilterEntity);
} catch (Exception e) {
return super.choose(key);
}
}
#location 4
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private void applyVersionFilter(String consumerServiceId, String consumerServiceVersion, String providerServiceId, List<ServiceInstance> instances) {
// 如果消费端未配置版本号,那么它可以调用提供端所有服务,需要符合规范,极力避免该情况发生
if (StringUtils.isEmpty(consumerServiceVersion)) {
return;
}
DiscoveryEntity discoveryEntity = pluginEntity.getDiscoveryEntity();
if (discoveryEntity == null) {
return;
}
Map<String, List<DiscoveryServiceEntity>> serviceEntityMap = discoveryEntity.getServiceEntityMap();
if (MapUtils.isEmpty(serviceEntityMap)) {
return;
}
List<DiscoveryServiceEntity> serviceEntityList = serviceEntityMap.get(consumerServiceId);
if (CollectionUtils.isEmpty(serviceEntityList)) {
return;
}
// 当前版本的消费端所能调用提供端的版本号列表
List<String> allFilterValueList = new ArrayList<String>();
for (DiscoveryServiceEntity serviceEntity : serviceEntityList) {
String providerServiceName = serviceEntity.getProviderServiceName();
if (StringUtils.equals(providerServiceName, providerServiceId)) {
List<String> consumerVersionValueList = serviceEntity.getConsumerVersionValueList();
List<String> providerVersionValueList = serviceEntity.getProviderVersionValueList();
// 判断consumer-version-value值是否包含当前消费端的版本号
if (CollectionUtils.isNotEmpty(consumerVersionValueList) && consumerVersionValueList.contains(consumerServiceVersion)) {
if (CollectionUtils.isNotEmpty(providerVersionValueList)) {
allFilterValueList.addAll(providerVersionValueList);
}
}
}
}
// 未找到相应的版本定义或者未定义
if (CollectionUtils.isEmpty(allFilterValueList)) {
return;
}
Iterator<ServiceInstance> iterator = instances.iterator();
while (iterator.hasNext()) {
ServiceInstance serviceInstance = iterator.next();
String metaDataVersion = serviceInstance.getMetadata().get(PluginConstant.VRESION);
if (!allFilterValueList.contains(metaDataVersion)) {
iterator.remove();
}
}
} | #vulnerable code
private void applyVersionFilter(String consumerServiceId, String consumerServiceVersion, String providerServiceId, List<ServiceInstance> instances) {
// 如果消费端未配置版本号,那么它可以调用提供端所有服务,需要符合规范,极力避免该情况发生
if (StringUtils.isEmpty(consumerServiceVersion)) {
return;
}
DiscoveryEntity discoveryEntity = pluginEntity.getDiscoveryEntity();
if (discoveryEntity == null) {
return;
}
Map<String, List<DiscoveryServiceEntity>> serviceEntityMap = discoveryEntity.getServiceEntityMap();
if (MapUtils.isEmpty(serviceEntityMap)) {
return;
}
List<DiscoveryServiceEntity> serviceEntityList = serviceEntityMap.get(consumerServiceId);
if (CollectionUtils.isEmpty(serviceEntityList)) {
return;
}
// 当前版本的消费端所能调用提供端的版本号列表
List<String> allFilterVersions = new ArrayList<String>();
for (DiscoveryServiceEntity serviceEntity : serviceEntityList) {
String providerServiceName = serviceEntity.getProviderServiceName();
if (StringUtils.equals(providerServiceName, providerServiceId)) {
String consumerVersionValue = serviceEntity.getConsumerVersionValue();
String providerVersionValue = serviceEntity.getProviderVersionValue();
List<String> consumerVersionList = getVersionList(consumerVersionValue);
List<String> providerVersionList = getVersionList(providerVersionValue);
// 判断consumer-version-value值是否包含当前消费端的版本号
if (CollectionUtils.isNotEmpty(consumerVersionList) && consumerVersionList.contains(consumerServiceVersion)) {
if (CollectionUtils.isNotEmpty(providerVersionList)) {
allFilterVersions.addAll(providerVersionList);
}
}
}
}
// 未找到相应的版本定义或者未定义
if (CollectionUtils.isEmpty(allFilterVersions)) {
return;
}
Iterator<ServiceInstance> iterator = instances.iterator();
while (iterator.hasNext()) {
ServiceInstance serviceInstance = iterator.next();
String metaDataVersion = serviceInstance.getMetadata().get(PluginConstant.VRESION);
if (!allFilterVersions.contains(metaDataVersion)) {
iterator.remove();
}
}
}
#location 34
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void mdcLocal() {
if (!traceLoggerEnabled) {
return;
}
Map<String, String> customizationMap = getCustomizationMap();
if (MapUtils.isNotEmpty(customizationMap)) {
for (Map.Entry<String, String> entry : customizationMap.entrySet()) {
MDC.put(entry.getKey(), (traceLoggerMdcKeyShown ? entry.getKey() + "=" : StringUtils.EMPTY) + entry.getValue());
}
}
String traceId = getTraceId();
String spanId = getSpanId();
MDC.put(DiscoveryConstant.TRACE_ID, (traceLoggerMdcKeyShown ? DiscoveryConstant.TRACE_ID + "=" : StringUtils.EMPTY) + (StringUtils.isNotEmpty(traceId) ? traceId : StringUtils.EMPTY));
MDC.put(DiscoveryConstant.SPAN_ID, (traceLoggerMdcKeyShown ? DiscoveryConstant.SPAN_ID + "=" : StringUtils.EMPTY) + (StringUtils.isNotEmpty(spanId) ? spanId : StringUtils.EMPTY));
MDC.put(DiscoveryConstant.N_D_SERVICE_GROUP, (traceLoggerMdcKeyShown ? DiscoveryConstant.N_D_SERVICE_GROUP + "=" : StringUtils.EMPTY) + pluginAdapter.getGroup());
MDC.put(DiscoveryConstant.N_D_SERVICE_TYPE, (traceLoggerMdcKeyShown ? DiscoveryConstant.N_D_SERVICE_TYPE + "=" : StringUtils.EMPTY) + pluginAdapter.getServiceType());
MDC.put(DiscoveryConstant.N_D_SERVICE_ID, (traceLoggerMdcKeyShown ? DiscoveryConstant.N_D_SERVICE_ID + "=" : StringUtils.EMPTY) + pluginAdapter.getServiceId());
MDC.put(DiscoveryConstant.N_D_SERVICE_ADDRESS, (traceLoggerMdcKeyShown ? DiscoveryConstant.N_D_SERVICE_ADDRESS + "=" : StringUtils.EMPTY) + pluginAdapter.getHost() + ":" + pluginAdapter.getPort());
MDC.put(DiscoveryConstant.N_D_SERVICE_VERSION, (traceLoggerMdcKeyShown ? DiscoveryConstant.N_D_SERVICE_VERSION + "=" : StringUtils.EMPTY) + pluginAdapter.getVersion());
MDC.put(DiscoveryConstant.N_D_SERVICE_REGION, (traceLoggerMdcKeyShown ? DiscoveryConstant.N_D_SERVICE_REGION + "=" : StringUtils.EMPTY) + pluginAdapter.getRegion());
LOG.debug("Trace chain information outputs to MDC...");
} | #vulnerable code
public void mdcLocal() {
if (!traceLoggerEnabled) {
return;
}
Map<String, String> customizationMap = getCustomizationMap();
if (MapUtils.isNotEmpty(customizationMap)) {
for (Map.Entry<String, String> entry : customizationMap.entrySet()) {
MDC.put(entry.getKey(), (traceLoggerMdcKeyShown ? entry.getKey() + "=" : StringUtils.EMPTY) + entry.getValue());
}
}
mdcUpdate();
MDC.put(DiscoveryConstant.N_D_SERVICE_GROUP, (traceLoggerMdcKeyShown ? DiscoveryConstant.N_D_SERVICE_GROUP + "=" : StringUtils.EMPTY) + pluginAdapter.getGroup());
MDC.put(DiscoveryConstant.N_D_SERVICE_TYPE, (traceLoggerMdcKeyShown ? DiscoveryConstant.N_D_SERVICE_TYPE + "=" : StringUtils.EMPTY) + pluginAdapter.getServiceType());
MDC.put(DiscoveryConstant.N_D_SERVICE_ID, (traceLoggerMdcKeyShown ? DiscoveryConstant.N_D_SERVICE_ID + "=" : StringUtils.EMPTY) + pluginAdapter.getServiceId());
MDC.put(DiscoveryConstant.N_D_SERVICE_ADDRESS, (traceLoggerMdcKeyShown ? DiscoveryConstant.N_D_SERVICE_ADDRESS + "=" : StringUtils.EMPTY) + pluginAdapter.getHost() + ":" + pluginAdapter.getPort());
MDC.put(DiscoveryConstant.N_D_SERVICE_VERSION, (traceLoggerMdcKeyShown ? DiscoveryConstant.N_D_SERVICE_VERSION + "=" : StringUtils.EMPTY) + pluginAdapter.getVersion());
MDC.put(DiscoveryConstant.N_D_SERVICE_REGION, (traceLoggerMdcKeyShown ? DiscoveryConstant.N_D_SERVICE_REGION + "=" : StringUtils.EMPTY) + pluginAdapter.getRegion());
LOG.debug("Trace chain information outputs to MDC...");
}
#location 8
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void mdcHeader() {
if (!traceLoggerEnabled) {
return;
}
Map<String, String> customizationMap = getCustomizationMap();
if (MapUtils.isNotEmpty(customizationMap)) {
for (Map.Entry<String, String> entry : customizationMap.entrySet()) {
MDC.put(entry.getKey(), (traceLoggerMdcKeyShown ? entry.getKey() + "=" : StringUtils.EMPTY) + entry.getValue());
}
}
String traceId = getTraceId();
String spanId = getSpanId();
MDC.put(DiscoveryConstant.TRACE_ID, (traceLoggerMdcKeyShown ? DiscoveryConstant.TRACE_ID + "=" : StringUtils.EMPTY) + (StringUtils.isNotEmpty(traceId) ? traceId : StringUtils.EMPTY));
MDC.put(DiscoveryConstant.SPAN_ID, (traceLoggerMdcKeyShown ? DiscoveryConstant.SPAN_ID + "=" : StringUtils.EMPTY) + (StringUtils.isNotEmpty(spanId) ? spanId : StringUtils.EMPTY));
MDC.put(DiscoveryConstant.N_D_SERVICE_GROUP, (traceLoggerMdcKeyShown ? DiscoveryConstant.N_D_SERVICE_GROUP + "=" : StringUtils.EMPTY) + strategyContextHolder.getHeader(DiscoveryConstant.N_D_SERVICE_GROUP));
MDC.put(DiscoveryConstant.N_D_SERVICE_TYPE, (traceLoggerMdcKeyShown ? DiscoveryConstant.N_D_SERVICE_TYPE + "=" : StringUtils.EMPTY) + strategyContextHolder.getHeader(DiscoveryConstant.N_D_SERVICE_TYPE));
MDC.put(DiscoveryConstant.N_D_SERVICE_ID, (traceLoggerMdcKeyShown ? DiscoveryConstant.N_D_SERVICE_ID + "=" : StringUtils.EMPTY) + strategyContextHolder.getHeader(DiscoveryConstant.N_D_SERVICE_ID));
MDC.put(DiscoveryConstant.N_D_SERVICE_ADDRESS, (traceLoggerMdcKeyShown ? DiscoveryConstant.N_D_SERVICE_ADDRESS + "=" : StringUtils.EMPTY) + strategyContextHolder.getHeader(DiscoveryConstant.N_D_SERVICE_ADDRESS));
MDC.put(DiscoveryConstant.N_D_SERVICE_VERSION, (traceLoggerMdcKeyShown ? DiscoveryConstant.N_D_SERVICE_VERSION + "=" : StringUtils.EMPTY) + strategyContextHolder.getHeader(DiscoveryConstant.N_D_SERVICE_VERSION));
MDC.put(DiscoveryConstant.N_D_SERVICE_REGION, (traceLoggerMdcKeyShown ? DiscoveryConstant.N_D_SERVICE_REGION + "=" : StringUtils.EMPTY) + strategyContextHolder.getHeader(DiscoveryConstant.N_D_SERVICE_REGION));
LOG.debug("Trace chain information outputs to MDC...");
} | #vulnerable code
public void mdcHeader() {
if (!traceLoggerEnabled) {
return;
}
Map<String, String> customizationMap = getCustomizationMap();
if (MapUtils.isNotEmpty(customizationMap)) {
for (Map.Entry<String, String> entry : customizationMap.entrySet()) {
MDC.put(entry.getKey(), (traceLoggerMdcKeyShown ? entry.getKey() + "=" : StringUtils.EMPTY) + entry.getValue());
}
}
mdcUpdate();
MDC.put(DiscoveryConstant.N_D_SERVICE_GROUP, (traceLoggerMdcKeyShown ? DiscoveryConstant.N_D_SERVICE_GROUP + "=" : StringUtils.EMPTY) + strategyContextHolder.getHeader(DiscoveryConstant.N_D_SERVICE_GROUP));
MDC.put(DiscoveryConstant.N_D_SERVICE_TYPE, (traceLoggerMdcKeyShown ? DiscoveryConstant.N_D_SERVICE_TYPE + "=" : StringUtils.EMPTY) + strategyContextHolder.getHeader(DiscoveryConstant.N_D_SERVICE_TYPE));
MDC.put(DiscoveryConstant.N_D_SERVICE_ID, (traceLoggerMdcKeyShown ? DiscoveryConstant.N_D_SERVICE_ID + "=" : StringUtils.EMPTY) + strategyContextHolder.getHeader(DiscoveryConstant.N_D_SERVICE_ID));
MDC.put(DiscoveryConstant.N_D_SERVICE_ADDRESS, (traceLoggerMdcKeyShown ? DiscoveryConstant.N_D_SERVICE_ADDRESS + "=" : StringUtils.EMPTY) + strategyContextHolder.getHeader(DiscoveryConstant.N_D_SERVICE_ADDRESS));
MDC.put(DiscoveryConstant.N_D_SERVICE_VERSION, (traceLoggerMdcKeyShown ? DiscoveryConstant.N_D_SERVICE_VERSION + "=" : StringUtils.EMPTY) + strategyContextHolder.getHeader(DiscoveryConstant.N_D_SERVICE_VERSION));
MDC.put(DiscoveryConstant.N_D_SERVICE_REGION, (traceLoggerMdcKeyShown ? DiscoveryConstant.N_D_SERVICE_REGION + "=" : StringUtils.EMPTY) + strategyContextHolder.getHeader(DiscoveryConstant.N_D_SERVICE_REGION));
LOG.debug("Trace chain information outputs to MDC...");
}
#location 8
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void debugHeader() {
if (!traceDebugEnabled) {
return;
}
System.out.println("---------------- Trace Information ---------------");
String traceId = getTraceId();
String spanId = getSpanId();
System.out.println(DiscoveryConstant.TRACE_ID + "=" + (StringUtils.isNotEmpty(traceId) ? traceId : StringUtils.EMPTY));
System.out.println(DiscoveryConstant.SPAN_ID + "=" + (StringUtils.isNotEmpty(spanId) ? spanId : StringUtils.EMPTY));
System.out.println(DiscoveryConstant.N_D_SERVICE_GROUP + "=" + strategyContextHolder.getHeader(DiscoveryConstant.N_D_SERVICE_GROUP));
System.out.println(DiscoveryConstant.N_D_SERVICE_TYPE + "=" + strategyContextHolder.getHeader(DiscoveryConstant.N_D_SERVICE_TYPE));
System.out.println(DiscoveryConstant.N_D_SERVICE_ID + "=" + strategyContextHolder.getHeader(DiscoveryConstant.N_D_SERVICE_ID));
System.out.println(DiscoveryConstant.N_D_SERVICE_ADDRESS + "=" + strategyContextHolder.getHeader(DiscoveryConstant.N_D_SERVICE_ADDRESS));
System.out.println(DiscoveryConstant.N_D_SERVICE_VERSION + "=" + strategyContextHolder.getHeader(DiscoveryConstant.N_D_SERVICE_VERSION));
System.out.println(DiscoveryConstant.N_D_SERVICE_REGION + "=" + strategyContextHolder.getHeader(DiscoveryConstant.N_D_SERVICE_REGION));
System.out.println(DiscoveryConstant.N_D_SERVICE_ENVIRONMENT + "=" + strategyContextHolder.getHeader(DiscoveryConstant.N_D_SERVICE_ENVIRONMENT));
String routeVersion = strategyContextHolder.getHeader(DiscoveryConstant.N_D_VERSION);
if (StringUtils.isNotEmpty(routeVersion)) {
System.out.println(DiscoveryConstant.N_D_VERSION + "=" + routeVersion);
}
String routeRegion = strategyContextHolder.getHeader(DiscoveryConstant.N_D_REGION);
if (StringUtils.isNotEmpty(routeRegion)) {
System.out.println(DiscoveryConstant.N_D_REGION + "=" + routeRegion);
}
String routeAddress = strategyContextHolder.getHeader(DiscoveryConstant.N_D_ADDRESS);
if (StringUtils.isNotEmpty(routeAddress)) {
System.out.println(DiscoveryConstant.N_D_ADDRESS + "=" + routeAddress);
}
String routeEnvironment = strategyContextHolder.getHeader(DiscoveryConstant.N_D_ENVIRONMENT);
if (StringUtils.isNotEmpty(routeEnvironment)) {
System.out.println(DiscoveryConstant.N_D_ENVIRONMENT + "=" + routeEnvironment);
}
String routeVersionWeight = strategyContextHolder.getHeader(DiscoveryConstant.N_D_VERSION_WEIGHT);
if (StringUtils.isNotEmpty(routeVersionWeight)) {
System.out.println(DiscoveryConstant.N_D_VERSION_WEIGHT + "=" + routeVersionWeight);
}
String routeRegionWeight = strategyContextHolder.getHeader(DiscoveryConstant.N_D_REGION_WEIGHT);
if (StringUtils.isNotEmpty(routeRegionWeight)) {
System.out.println(DiscoveryConstant.N_D_REGION_WEIGHT + "=" + routeRegionWeight);
}
Map<String, String> customizationMap = getCustomizationMap();
if (MapUtils.isNotEmpty(customizationMap)) {
for (Map.Entry<String, String> entry : customizationMap.entrySet()) {
System.out.println(entry.getKey() + "=" + entry.getValue());
}
}
System.out.println("--------------------------------------------------");
} | #vulnerable code
public void debugHeader() {
if (!traceDebugEnabled) {
return;
}
System.out.println("---------------- Trace Information ---------------");
String traceId = getTraceId();
String spanId = getSpanId();
System.out.println(DiscoveryConstant.TRACE_ID + "=" + (StringUtils.isNotEmpty(traceId) ? traceId : StringUtils.EMPTY));
System.out.println(DiscoveryConstant.SPAN_ID + "=" + (StringUtils.isNotEmpty(spanId) ? spanId : StringUtils.EMPTY));
System.out.println(DiscoveryConstant.N_D_SERVICE_GROUP + "=" + strategyContextHolder.getHeader(DiscoveryConstant.N_D_SERVICE_GROUP));
System.out.println(DiscoveryConstant.N_D_SERVICE_TYPE + "=" + strategyContextHolder.getHeader(DiscoveryConstant.N_D_SERVICE_TYPE));
System.out.println(DiscoveryConstant.N_D_SERVICE_ID + "=" + strategyContextHolder.getHeader(DiscoveryConstant.N_D_SERVICE_ID));
System.out.println(DiscoveryConstant.N_D_SERVICE_ADDRESS + "=" + strategyContextHolder.getHeader(DiscoveryConstant.N_D_SERVICE_ADDRESS));
System.out.println(DiscoveryConstant.N_D_SERVICE_VERSION + "=" + strategyContextHolder.getHeader(DiscoveryConstant.N_D_SERVICE_VERSION));
System.out.println(DiscoveryConstant.N_D_SERVICE_REGION + "=" + strategyContextHolder.getHeader(DiscoveryConstant.N_D_SERVICE_REGION));
System.out.println(DiscoveryConstant.N_D_SERVICE_ENVIRONMENT + "=" + strategyContextHolder.getHeader(DiscoveryConstant.N_D_SERVICE_ENVIRONMENT));
String routeVersion = strategyContextHolder.getHeader(DiscoveryConstant.N_D_VERSION);
if (StringUtils.isNotEmpty(routeVersion)) {
System.out.println(DiscoveryConstant.N_D_VERSION + "=" + routeVersion);
}
String routeRegion = strategyContextHolder.getHeader(DiscoveryConstant.N_D_REGION);
if (StringUtils.isNotEmpty(routeRegion)) {
System.out.println(DiscoveryConstant.N_D_REGION + "=" + routeRegion);
}
String routeAddress = strategyContextHolder.getHeader(DiscoveryConstant.N_D_ADDRESS);
if (StringUtils.isNotEmpty(routeAddress)) {
System.out.println(DiscoveryConstant.N_D_ADDRESS + "=" + routeAddress);
}
String routeVersionWeight = strategyContextHolder.getHeader(DiscoveryConstant.N_D_VERSION_WEIGHT);
if (StringUtils.isNotEmpty(routeVersionWeight)) {
System.out.println(DiscoveryConstant.N_D_VERSION_WEIGHT + "=" + routeVersionWeight);
}
String routeRegionWeight = strategyContextHolder.getHeader(DiscoveryConstant.N_D_REGION_WEIGHT);
if (StringUtils.isNotEmpty(routeRegionWeight)) {
System.out.println(DiscoveryConstant.N_D_REGION_WEIGHT + "=" + routeRegionWeight);
}
Map<String, String> customizationMap = getCustomizationMap();
if (MapUtils.isNotEmpty(customizationMap)) {
for (Map.Entry<String, String> entry : customizationMap.entrySet()) {
System.out.println(entry.getKey() + "=" + entry.getValue());
}
}
System.out.println("--------------------------------------------------");
}
#location 42
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private String createSpanId() {
try {
return StrategySkywalkingTracerResolver.getSpanId();
} catch (Exception e) {
return null;
}
} | #vulnerable code
private String createSpanId() {
if (System.getProperties().get("skywalking.agent.service_name") == null) {
return null;
}
try {
Object traceContext = StrategySkywalkingTracerResolver.invokeStaticMethod("org.apache.skywalking.apm.agent.core.context.ContextManager", "get");
if (traceContext != null) {
if (traceContext.getClass().getName().equals("org.apache.skywalking.apm.agent.core.context.TracingContext")) {
Field fieldSegment = StrategySkywalkingTracerResolver.findField(traceContext.getClass(), "segment");
Object segment = StrategySkywalkingTracerResolver.getField(fieldSegment, traceContext);
Field fieldSegmentId = StrategySkywalkingTracerResolver.findField(segment.getClass(), "traceSegmentId");
String segmentId = StrategySkywalkingTracerResolver.getField(fieldSegmentId, segment).toString();
return segmentId;
} else {
return null;
}
}
} catch (Exception e) {
}
return null;
}
#location 11
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private boolean applyFromHeader(Server server, Map<String, String> metadata) {
String mobile = zuulStrategyContextHolder.getHeader("mobile");
String version = metadata.get(DiscoveryConstant.VERSION);
String serviceId = pluginAdapter.getServerServiceId(server);
LOG.info("Zuul端负载均衡用户定制触发:mobile={}, serviceId={}, metadata={}", mobile, serviceId, metadata);
if (StringUtils.isNotEmpty(mobile)) {
// 手机号以移动138开头,路由到1.0版本的服务上
if (mobile.startsWith("138") && StringUtils.equals(version, "1.0")) {
return true;
// 手机号以联通133开头,路由到2.0版本的服务上
} else if (mobile.startsWith("133") && StringUtils.equals(version, "1.1")) {
return true;
} else {
// 其它情况,直接拒绝请求
return false;
}
}
return true;
} | #vulnerable code
private boolean applyFromHeader(Server server, Map<String, String> metadata) {
String token = zuulStrategyContextHolder.getHeader("token");
String serviceId = pluginAdapter.getServerServiceId(server);
LOG.info("Zuul端负载均衡用户定制触发:token={}, serviceId={}, metadata={}", token, serviceId, metadata);
String filterToken = "abc";
if (StringUtils.isNotEmpty(token) && token.contains(filterToken)) {
LOG.info("过滤条件:当Token含有'{}'的时候,不能被Ribbon负载均衡到", filterToken);
return false;
}
return true;
}
#location 8
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@SuppressWarnings("rawtypes")
private void parseStrategyCondition(Element element, List<StrategyConditionEntity> strategyConditionEntityList) {
for (Iterator elementIterator = element.elementIterator(); elementIterator.hasNext();) {
Object childElementObject = elementIterator.next();
if (childElementObject instanceof Element) {
Element childElement = (Element) childElementObject;
if (StringUtils.equals(childElement.getName(), ConfigConstant.CONDITION_ELEMENT_NAME)) {
StrategyConditionEntity strategyConditionEntity = new StrategyConditionEntity();
Attribute idAttribute = childElement.attribute(ConfigConstant.ID_ATTRIBUTE_NAME);
if (idAttribute == null) {
throw new DiscoveryException("Attribute[" + ConfigConstant.ID_ATTRIBUTE_NAME + "] in element[" + childElement.getName() + "] is missing");
}
String id = idAttribute.getData().toString().trim();
strategyConditionEntity.setId(id);
Attribute headerAttribute = childElement.attribute(ConfigConstant.HEADER_ATTRIBUTE_NAME);
if (headerAttribute == null) {
throw new DiscoveryException("Attribute[" + ConfigConstant.HEADER_ATTRIBUTE_NAME + "] in element[" + childElement.getName() + "] is missing");
}
String header = headerAttribute.getData().toString().trim();
strategyConditionEntity.setConditionHeader(header);
Attribute versionIdAttribute = childElement.attribute(ConfigConstant.VERSION_ELEMENT_NAME + DiscoveryConstant.DASH + ConfigConstant.ID_ATTRIBUTE_NAME);
if (versionIdAttribute != null) {
String versionId = versionIdAttribute.getData().toString().trim();
strategyConditionEntity.setVersionId(versionId);
}
Attribute regionIdAttribute = childElement.attribute(ConfigConstant.REGION_ELEMENT_NAME + DiscoveryConstant.DASH + ConfigConstant.ID_ATTRIBUTE_NAME);
if (regionIdAttribute != null) {
String regionId = regionIdAttribute.getData().toString().trim();
strategyConditionEntity.setRegionId(regionId);
}
Attribute addressIdAttribute = childElement.attribute(ConfigConstant.ADDRESS_ELEMENT_NAME + DiscoveryConstant.DASH + ConfigConstant.ID_ATTRIBUTE_NAME);
if (addressIdAttribute != null) {
String addressId = addressIdAttribute.getData().toString().trim();
strategyConditionEntity.setAddressId(addressId);
}
Attribute versionWeightIdAttribute = childElement.attribute(ConfigConstant.VERSION_WEIGHT_ELEMENT_NAME + DiscoveryConstant.DASH + ConfigConstant.ID_ATTRIBUTE_NAME);
if (versionWeightIdAttribute != null) {
String versionWeightId = versionWeightIdAttribute.getData().toString().trim();
strategyConditionEntity.setVersionWeightId(versionWeightId);
}
Attribute regionWeightIdAttribute = childElement.attribute(ConfigConstant.REGION_WEIGHT_ELEMENT_NAME + DiscoveryConstant.DASH + ConfigConstant.ID_ATTRIBUTE_NAME);
if (regionWeightIdAttribute != null) {
String regionWeightId = regionWeightIdAttribute.getData().toString().trim();
strategyConditionEntity.setRegionWeightId(regionWeightId);
}
strategyConditionEntityList.add(strategyConditionEntity);
}
}
}
} | #vulnerable code
@SuppressWarnings("rawtypes")
private void parseStrategyCondition(Element element, List<StrategyConditionEntity> strategyConditionEntityList) {
for (Iterator elementIterator = element.elementIterator(); elementIterator.hasNext();) {
Object childElementObject = elementIterator.next();
if (childElementObject instanceof Element) {
Element childElement = (Element) childElementObject;
if (StringUtils.equals(childElement.getName(), ConfigConstant.CONDITION_ELEMENT_NAME)) {
StrategyConditionEntity strategyConditionEntity = new StrategyConditionEntity();
Attribute idAttribute = childElement.attribute(ConfigConstant.ID_ATTRIBUTE_NAME);
if (idAttribute == null) {
throw new DiscoveryException("Attribute[" + ConfigConstant.ID_ATTRIBUTE_NAME + "] in element[" + childElement.getName() + "] is missing");
}
String id = idAttribute.getData().toString().trim();
strategyConditionEntity.setId(id);
Attribute headerAttribute = childElement.attribute(ConfigConstant.HEADER_ATTRIBUTE_NAME);
if (headerAttribute == null) {
throw new DiscoveryException("Attribute[" + ConfigConstant.HEADER_ATTRIBUTE_NAME + "] in element[" + childElement.getName() + "] is missing");
}
String header = headerAttribute.getData().toString().trim();
strategyConditionEntity.setConditionHeader(header);
List<String> headerList = StringUtil.splitToList(header, DiscoveryConstant.SEPARATE);
for (String value : headerList) {
String[] valueArray = StringUtils.split(value, DiscoveryConstant.EQUALS);
String headerName = valueArray[0].trim();
String headerValue = valueArray[1].trim();
strategyConditionEntity.getConditionHeaderMap().put(headerName, headerValue);
}
Attribute versionIdAttribute = childElement.attribute(ConfigConstant.VERSION_ELEMENT_NAME + DiscoveryConstant.DASH + ConfigConstant.ID_ATTRIBUTE_NAME);
if (versionIdAttribute != null) {
String versionId = versionIdAttribute.getData().toString().trim();
strategyConditionEntity.setVersionId(versionId);
}
Attribute regionIdAttribute = childElement.attribute(ConfigConstant.REGION_ELEMENT_NAME + DiscoveryConstant.DASH + ConfigConstant.ID_ATTRIBUTE_NAME);
if (regionIdAttribute != null) {
String regionId = regionIdAttribute.getData().toString().trim();
strategyConditionEntity.setRegionId(regionId);
}
Attribute addressIdAttribute = childElement.attribute(ConfigConstant.ADDRESS_ELEMENT_NAME + DiscoveryConstant.DASH + ConfigConstant.ID_ATTRIBUTE_NAME);
if (addressIdAttribute != null) {
String addressId = addressIdAttribute.getData().toString().trim();
strategyConditionEntity.setAddressId(addressId);
}
Attribute versionWeightIdAttribute = childElement.attribute(ConfigConstant.VERSION_WEIGHT_ELEMENT_NAME + DiscoveryConstant.DASH + ConfigConstant.ID_ATTRIBUTE_NAME);
if (versionWeightIdAttribute != null) {
String versionWeightId = versionWeightIdAttribute.getData().toString().trim();
strategyConditionEntity.setVersionWeightId(versionWeightId);
}
Attribute regionWeightIdAttribute = childElement.attribute(ConfigConstant.REGION_WEIGHT_ELEMENT_NAME + DiscoveryConstant.DASH + ConfigConstant.ID_ATTRIBUTE_NAME);
if (regionWeightIdAttribute != null) {
String regionWeightId = regionWeightIdAttribute.getData().toString().trim();
strategyConditionEntity.setRegionWeightId(regionWeightId);
}
strategyConditionEntityList.add(strategyConditionEntity);
}
}
}
}
#location 25
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private boolean applyFromHeader(Server server, Map<String, String> metadata) {
String mobile = gatewayStrategyContextHolder.getHeader("mobile");
String version = metadata.get(DiscoveryConstant.VERSION);
String serviceId = pluginAdapter.getServerServiceId(server);
LOG.info("Gateway端负载均衡用户定制触发:mobile={}, serviceId={}, metadata={}", mobile, serviceId, metadata);
if (StringUtils.isNotEmpty(mobile)) {
// 手机号以移动138开头,路由到1.0版本的服务上
if (mobile.startsWith("138") && StringUtils.equals(version, "1.0")) {
return true;
// 手机号以联通133开头,路由到2.0版本的服务上
} else if (mobile.startsWith("133") && StringUtils.equals(version, "1.1")) {
return true;
} else {
// 其它情况,直接拒绝请求
return false;
}
}
return true;
} | #vulnerable code
private boolean applyFromHeader(Server server, Map<String, String> metadata) {
String token = gatewayStrategyContextHolder.getHeader("token");
String serviceId = pluginAdapter.getServerServiceId(server);
LOG.info("Gateway端负载均衡用户定制触发:token={}, serviceId={}, metadata={}", token, serviceId, metadata);
String filterToken = "abc";
if (StringUtils.isNotEmpty(token) && token.contains(filterToken)) {
LOG.info("过滤条件:当Token含有'{}'的时候,不能被Ribbon负载均衡到", filterToken);
return false;
}
return true;
}
#location 8
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public int compare(@Nullable Object left, @Nullable Object right) throws SpelEvaluationException {
if (left == null) {
return right == null ? 0 : -1;
} else if (right == null) {
return 1;
}
try {
BigDecimal leftValue = new BigDecimal(left.toString());
BigDecimal rightValue = new BigDecimal(right.toString());
return super.compare(leftValue, rightValue);
} catch (Exception e) {
}
return super.compare(left, right);
} | #vulnerable code
@Override
public int compare(@Nullable Object left, @Nullable Object right) throws SpelEvaluationException {
if (left == null) {
return 0;
}
try {
BigDecimal leftValue = new BigDecimal(left.toString());
BigDecimal rightValue = new BigDecimal(right.toString());
return super.compare(leftValue, rightValue);
} catch (Exception e) {
}
return super.compare(left, right);
}
#location 9
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void update(N node) {
Point2D location = layoutModel.apply(node);
if (!this.getLayoutArea().contains(location)) {
log.trace(location + " outside of spatial " + this.getLayoutArea());
this.setBounds(this.getUnion(this.getLayoutArea(), location));
this.recalculate(layoutModel.getGraph().nodes());
}
SpatialQuadTree<N> locationContainingLeaf = getContainingQuadTreeLeaf(location);
log.trace("leaf {} contains {}", locationContainingLeaf, location);
SpatialQuadTree<N> nodeContainingLeaf = getContainingQuadTreeLeaf(node);
log.trace("leaf {} contains node {}", nodeContainingLeaf, node);
if (locationContainingLeaf == null) {
log.error("got null for leaf containing {}", location);
}
if (nodeContainingLeaf == null) {
log.warn("got null for leaf containing {}", node);
}
if (locationContainingLeaf != null && !locationContainingLeaf.equals(nodeContainingLeaf)) {
log.trace("time to recalculate");
this.recalculate(layoutModel.getGraph().nodes());
}
this.insert(node);
} | #vulnerable code
@Override
public void update(N node) {
Point2D location = layoutModel.apply(node);
if (!this.getLayoutArea().contains(location)) {
log.trace(location + " outside of spatial " + this.getLayoutArea());
this.setBounds(this.getUnion(this.getLayoutArea(), location));
this.recalculate(layoutModel.getGraph().nodes());
}
SpatialQuadTree<N> locationContainingLeaf = getContainingQuadTreeLeaf(location);
log.trace("leaf {} contains {}", locationContainingLeaf, location);
SpatialQuadTree<N> nodeContainingLeaf = getContainingQuadTreeLeaf(node);
log.trace("leaf {} contains node {}", nodeContainingLeaf, node);
if (locationContainingLeaf == null) {
log.error("got null for leaf containing {}", location);
}
if (nodeContainingLeaf == null) {
log.warn("got null for leaf containing {}", node);
}
if (!locationContainingLeaf.equals(nodeContainingLeaf)) {
log.trace("time to recalculate");
this.recalculate(layoutModel.getGraph().nodes());
}
this.insert(node);
}
#location 19
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void testBasicWrite() throws IOException, ParserConfigurationException, SAXException {
Network<String, Number> g = TestGraphs.createTestGraph(true);
GraphMLWriter<String, Number> gmlw = new GraphMLWriter<String, Number>();
Function<Number, String> edge_weight =
new Function<Number, String>() {
public String apply(Number n) {
return String.valueOf(n.intValue());
}
};
Function<String, String> vertex_name = Function.identity();
//TransformerUtils.nopTransformer();
gmlw.addEdgeData("weight", "integer value for the edge", Integer.toString(-1), edge_weight);
gmlw.addVertexData("name", "identifier for the vertex", null, vertex_name);
gmlw.setEdgeIDs(edge_weight);
gmlw.setVertexIDs(vertex_name);
gmlw.save(g, new FileWriter("src/test/resources/testbasicwrite.graphml"));
// TODO: now read it back in and compare the graph connectivity
// and other metadata with what's in TestGraphs.pairs[], etc.
GraphMLReader<MutableNetwork<String, Object>, String, Object> gmlr =
new GraphMLReader<MutableNetwork<String, Object>, String, Object>();
MutableNetwork<String, Object> g2 = NetworkBuilder.directed().allowsSelfLoops(true).build();
gmlr.load("src/test/resources/testbasicwrite.graphml", g2);
Map<String, GraphMLMetadata<Object>> edge_metadata = gmlr.getEdgeMetadata();
Function<Object, String> edge_weight2 = edge_metadata.get("weight").transformer;
validateTopology(g, g2, edge_weight, edge_weight2);
File f = new File("src/test/resources/testbasicwrite.graphml");
f.delete();
} | #vulnerable code
public void testBasicWrite() throws IOException, ParserConfigurationException, SAXException {
Network<String, Number> g = TestGraphs.createTestGraph(true);
GraphMLWriter<String, Number> gmlw = new GraphMLWriter<String, Number>();
Function<Number, String> edge_weight =
new Function<Number, String>() {
public String apply(Number n) {
return String.valueOf(n.intValue());
}
};
Function<String, String> vertex_name = Functions.identity();
//TransformerUtils.nopTransformer();
gmlw.addEdgeData("weight", "integer value for the edge", Integer.toString(-1), edge_weight);
gmlw.addVertexData("name", "identifier for the vertex", null, vertex_name);
gmlw.setEdgeIDs(edge_weight);
gmlw.setVertexIDs(vertex_name);
gmlw.save(g, new FileWriter("src/test/resources/testbasicwrite.graphml"));
// TODO: now read it back in and compare the graph connectivity
// and other metadata with what's in TestGraphs.pairs[], etc.
GraphMLReader<MutableNetwork<String, Object>, String, Object> gmlr =
new GraphMLReader<MutableNetwork<String, Object>, String, Object>();
MutableNetwork<String, Object> g2 = NetworkBuilder.directed().allowsSelfLoops(true).build();
gmlr.load("src/test/resources/testbasicwrite.graphml", g2);
Map<String, GraphMLMetadata<Object>> edge_metadata = gmlr.getEdgeMetadata();
Function<Object, String> edge_weight2 = edge_metadata.get("weight").transformer;
validateTopology(g, g2, edge_weight, edge_weight2);
File f = new File("src/test/resources/testbasicwrite.graphml");
f.delete();
}
#location 18
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
protected V getClosest(
SpatialQuadTree<V> spatial, LayoutModel<V, Point2D> layoutModel, double x, double y) {
// move the x,y to layout coordinates
Point2D pickPointInView = new Point2D.Double(x, y);
Point2D pickPointInLayout =
vv.getRenderContext()
.getMultiLayerTransformer()
.inverseTransform(Layer.LAYOUT, pickPointInView);
if (log.isTraceEnabled()) {
log.trace("pickPoint in view {} layout {}", pickPointInView, pickPointInLayout);
}
double lx = pickPointInLayout.getX();
double ly = pickPointInLayout.getY();
SpatialQuadTree<V> leaf = spatial.getContainingQuadTreeLeaf(lx, ly);
if (log.isTraceEnabled()) {
log.trace("leaf for {},{} is {}", lx, ly, leaf);
}
if (leaf == null) return null;
double diameter = leaf.getLayoutArea().getWidth();
double radius = diameter / 2;
double minDistance = Double.MAX_VALUE;
V closest = null;
Ellipse2D target = new Ellipse2D.Double(lx - radius, ly - radius, diameter, diameter);
if (log.isTraceEnabled()) {
log.trace("target is {}", target);
}
Collection<V> nodes = spatial.getVisibleNodes(target);
if (log.isTraceEnabled()) {
log.trace("instead of checking all nodes: {}", getFilteredVertices());
log.trace("out of these candidates: {}...", nodes);
}
for (V node : nodes) {
Shape shape = vv.getRenderContext().getVertexShapeTransformer().apply(node);
// get the vertex location
Point2D p = layoutModel.apply(node);
if (p == null) {
continue;
}
// transform the vertex location to screen coords
p = vv.getRenderContext().getMultiLayerTransformer().transform(Layer.LAYOUT, p);
double ox = x - p.getX();
double oy = y - p.getY();
if (shape.contains(ox, oy)) {
if (style == Style.LOWEST) {
// return the first match
return node;
} else if (style == Style.HIGHEST) {
// will return the last match
closest = node;
} else {
// return the vertex closest to the
// center of a vertex shape
Rectangle2D bounds = shape.getBounds2D();
double dx = bounds.getCenterX() - ox;
double dy = bounds.getCenterY() - oy;
double dist = dx * dx + dy * dy;
if (dist < minDistance) {
minDistance = dist;
closest = node;
}
}
}
}
if (log.isTraceEnabled()) {
log.trace("picked {} with spatial quadtree", closest);
}
return closest;
} | #vulnerable code
protected V getClosest(
SpatialQuadTree<V> spatial, LayoutModel<V, Point2D> layoutModel, double x, double y) {
SpatialQuadTree<V> leaf = spatial.getContainingQuadTreeLeaf(x, y);
double diameter = leaf.getLayoutArea().getWidth();
double radius = diameter / 2;
double minDistance = Double.MAX_VALUE;
V closest = null;
Ellipse2D target = new Ellipse2D.Double(x - radius, y - radius, diameter, diameter);
Collection<V> nodes = spatial.getVisibleNodes(target);
if (log.isTraceEnabled()) {
log.trace("instead of checking all nodes: {}", getFilteredVertices());
log.trace("out of these candidates: {}...", nodes);
}
for (V node : nodes) {
Shape shape = vv.getRenderContext().getVertexShapeTransformer().apply(node);
// get the vertex location
Point2D p = layoutModel.apply(node);
if (p == null) {
continue;
}
// transform the vertex location to screen coords
p = vv.getRenderContext().getMultiLayerTransformer().transform(Layer.LAYOUT, p);
double ox = x - p.getX();
double oy = y - p.getY();
if (shape.contains(ox, oy)) {
if (style == Style.LOWEST) {
// return the first match
return node;
} else if (style == Style.HIGHEST) {
// will return the last match
closest = node;
} else {
// return the vertex closest to the
// center of a vertex shape
Rectangle2D bounds = shape.getBounds2D();
double dx = bounds.getCenterX() - ox;
double dy = bounds.getCenterY() - oy;
double dist = dx * dx + dy * dy;
if (dist < minDistance) {
minDistance = dist;
closest = node;
}
}
}
}
if (log.isTraceEnabled()) {
log.trace("picked {} with spatial quadtree", closest);
}
return closest;
}
#location 4
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void testBasicWrite() throws IOException, ParserConfigurationException, SAXException {
Network<String, Number> g = TestGraphs.createTestGraph(true);
GraphMLWriter<String, Number> gmlw = new GraphMLWriter<String, Number>();
Function<Number, String> edge_weight =
new Function<Number, String>() {
public String apply(Number n) {
return String.valueOf(n.intValue());
}
};
Function<String, String> vertex_name = Function.identity();
//TransformerUtils.nopTransformer();
gmlw.addEdgeData("weight", "integer value for the edge", Integer.toString(-1), edge_weight);
gmlw.addVertexData("name", "identifier for the vertex", null, vertex_name);
gmlw.setEdgeIDs(edge_weight);
gmlw.setVertexIDs(vertex_name);
gmlw.save(g, new FileWriter("src/test/resources/testbasicwrite.graphml"));
// TODO: now read it back in and compare the graph connectivity
// and other metadata with what's in TestGraphs.pairs[], etc.
GraphMLReader<MutableNetwork<String, Object>, String, Object> gmlr =
new GraphMLReader<MutableNetwork<String, Object>, String, Object>();
MutableNetwork<String, Object> g2 = NetworkBuilder.directed().allowsSelfLoops(true).build();
gmlr.load("src/test/resources/testbasicwrite.graphml", g2);
Map<String, GraphMLMetadata<Object>> edge_metadata = gmlr.getEdgeMetadata();
Function<Object, String> edge_weight2 = edge_metadata.get("weight").transformer;
validateTopology(g, g2, edge_weight, edge_weight2);
File f = new File("src/test/resources/testbasicwrite.graphml");
f.delete();
} | #vulnerable code
public void testBasicWrite() throws IOException, ParserConfigurationException, SAXException {
Network<String, Number> g = TestGraphs.createTestGraph(true);
GraphMLWriter<String, Number> gmlw = new GraphMLWriter<String, Number>();
Function<Number, String> edge_weight =
new Function<Number, String>() {
public String apply(Number n) {
return String.valueOf(n.intValue());
}
};
Function<String, String> vertex_name = Functions.identity();
//TransformerUtils.nopTransformer();
gmlw.addEdgeData("weight", "integer value for the edge", Integer.toString(-1), edge_weight);
gmlw.addVertexData("name", "identifier for the vertex", null, vertex_name);
gmlw.setEdgeIDs(edge_weight);
gmlw.setVertexIDs(vertex_name);
gmlw.save(g, new FileWriter("src/test/resources/testbasicwrite.graphml"));
// TODO: now read it back in and compare the graph connectivity
// and other metadata with what's in TestGraphs.pairs[], etc.
GraphMLReader<MutableNetwork<String, Object>, String, Object> gmlr =
new GraphMLReader<MutableNetwork<String, Object>, String, Object>();
MutableNetwork<String, Object> g2 = NetworkBuilder.directed().allowsSelfLoops(true).build();
gmlr.load("src/test/resources/testbasicwrite.graphml", g2);
Map<String, GraphMLMetadata<Object>> edge_metadata = gmlr.getEdgeMetadata();
Function<Object, String> edge_weight2 = edge_metadata.get("weight").transformer;
validateTopology(g, g2, edge_weight, edge_weight2);
File f = new File("src/test/resources/testbasicwrite.graphml");
f.delete();
}
#location 27
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Before
@SuppressWarnings({ "unchecked", "deprecation" })
public void before() throws IllegalArgumentException, IllegalAccessException, SQLException, SecurityException, NoSuchFieldException, CloneNotSupportedException{
driver = new MockJDBCDriver(new MockJDBCAnswer() {
public Connection answer() throws SQLException {
return new MockConnection();
}
});
mockConfig = EasyMock.createNiceMock(BoneCPConfig.class);
expect(mockConfig.clone()).andReturn(mockConfig).anyTimes();
expect(mockConfig.getPartitionCount()).andReturn(2).anyTimes();
expect(mockConfig.getMaxConnectionsPerPartition()).andReturn(1).anyTimes();
expect(mockConfig.getMinConnectionsPerPartition()).andReturn(1).anyTimes();
expect(mockConfig.getIdleConnectionTestPeriodInMinutes()).andReturn(0L).anyTimes();
expect(mockConfig.getIdleMaxAgeInMinutes()).andReturn(1000L).anyTimes();
expect(mockConfig.getUsername()).andReturn(CommonTestUtils.username).anyTimes();
expect(mockConfig.getPassword()).andReturn(CommonTestUtils.password).anyTimes();
expect(mockConfig.getJdbcUrl()).andReturn(CommonTestUtils.url).anyTimes();
expect(mockConfig.getReleaseHelperThreads()).andReturn(1).once().andReturn(0).anyTimes();
expect(mockConfig.getStatementReleaseHelperThreads()).andReturn(1).once().andReturn(0).anyTimes();
expect(mockConfig.getInitSQL()).andReturn(CommonTestUtils.TEST_QUERY).anyTimes();
expect(mockConfig.isCloseConnectionWatch()).andReturn(true).anyTimes();
expect(mockConfig.isLogStatementsEnabled()).andReturn(true).anyTimes();
expect(mockConfig.getConnectionTimeoutInMs()).andReturn(Long.MAX_VALUE).anyTimes();
expect(mockConfig.getServiceOrder()).andReturn("LIFO").anyTimes();
expect(mockConfig.getAcquireRetryDelayInMs()).andReturn(1000L).anyTimes();
expect(mockConfig.getPoolName()).andReturn("poolName").anyTimes();
expect(mockConfig.getPoolAvailabilityThreshold()).andReturn(20).anyTimes();
replay(mockConfig);
// once for no {statement, connection} release threads, once with release threads....
testClass = new BoneCP(mockConfig);
testClass = new BoneCP(mockConfig);
Field field = testClass.getClass().getDeclaredField("partitions");
field.setAccessible(true);
ConnectionPartition[] partitions = (ConnectionPartition[]) field.get(testClass);
// if all ok
assertEquals(2, partitions.length);
// switch to our mock version now
mockPartition = EasyMock.createNiceMock(ConnectionPartition.class);
Array.set(field.get(testClass), 0, mockPartition);
Array.set(field.get(testClass), 1, mockPartition);
mockKeepAliveScheduler = EasyMock.createNiceMock(ScheduledExecutorService.class);
field = testClass.getClass().getDeclaredField("keepAliveScheduler");
field.setAccessible(true);
field.set(testClass, mockKeepAliveScheduler);
field = testClass.getClass().getDeclaredField("connectionsScheduler");
field.setAccessible(true);
mockConnectionsScheduler = EasyMock.createNiceMock(ExecutorService.class);
field.set(testClass, mockConnectionsScheduler);
mockConnectionHandles = EasyMock.createNiceMock(BoundedLinkedTransferQueue.class);
mockConnection = EasyMock.createNiceMock(ConnectionHandle.class);
mockLock = EasyMock.createNiceMock(Lock.class);
mockLogger = TestUtils.mockLogger(testClass.getClass());
makeThreadSafe(mockLogger, true);
mockDatabaseMetadata = EasyMock.createNiceMock(DatabaseMetaData.class);
mockResultSet = EasyMock.createNiceMock(MockResultSet.class);
mockLogger.error((String)anyObject(), anyObject());
expectLastCall().anyTimes();
reset(mockConfig, mockKeepAliveScheduler, mockConnectionsScheduler, mockPartition,
mockConnectionHandles, mockConnection, mockLock);
} | #vulnerable code
@Before
@SuppressWarnings({ "unchecked", "deprecation" })
public void before() throws IllegalArgumentException, IllegalAccessException, SQLException, SecurityException, NoSuchFieldException, CloneNotSupportedException{
mockConfig = EasyMock.createNiceMock(BoneCPConfig.class);
expect(mockConfig.clone()).andReturn(mockConfig).anyTimes();
expect(mockConfig.getPartitionCount()).andReturn(2).anyTimes();
expect(mockConfig.getMaxConnectionsPerPartition()).andReturn(1).anyTimes();
expect(mockConfig.getMinConnectionsPerPartition()).andReturn(1).anyTimes();
expect(mockConfig.getIdleConnectionTestPeriodInMinutes()).andReturn(0L).anyTimes();
expect(mockConfig.getIdleMaxAgeInMinutes()).andReturn(1000L).anyTimes();
expect(mockConfig.getUsername()).andReturn(CommonTestUtils.username).anyTimes();
expect(mockConfig.getPassword()).andReturn(CommonTestUtils.password).anyTimes();
expect(mockConfig.getJdbcUrl()).andReturn(CommonTestUtils.url).anyTimes();
expect(mockConfig.getReleaseHelperThreads()).andReturn(1).once().andReturn(0).anyTimes();
expect(mockConfig.getStatementReleaseHelperThreads()).andReturn(1).once().andReturn(0).anyTimes();
expect(mockConfig.getInitSQL()).andReturn(CommonTestUtils.TEST_QUERY).anyTimes();
expect(mockConfig.isCloseConnectionWatch()).andReturn(true).anyTimes();
expect(mockConfig.isLogStatementsEnabled()).andReturn(true).anyTimes();
expect(mockConfig.getConnectionTimeoutInMs()).andReturn(Long.MAX_VALUE).anyTimes();
expect(mockConfig.getServiceOrder()).andReturn("LIFO").anyTimes();
expect(mockConfig.getAcquireRetryDelayInMs()).andReturn(1000L).anyTimes();
expect(mockConfig.getPoolName()).andReturn("poolName").anyTimes();
expect(mockConfig.getPoolAvailabilityThreshold()).andReturn(20).anyTimes();
replay(mockConfig);
// once for no {statement, connection} release threads, once with release threads....
testClass = new BoneCP(mockConfig);
testClass = new BoneCP(mockConfig);
Field field = testClass.getClass().getDeclaredField("partitions");
field.setAccessible(true);
ConnectionPartition[] partitions = (ConnectionPartition[]) field.get(testClass);
// if all ok
assertEquals(2, partitions.length);
// switch to our mock version now
mockPartition = EasyMock.createNiceMock(ConnectionPartition.class);
Array.set(field.get(testClass), 0, mockPartition);
Array.set(field.get(testClass), 1, mockPartition);
mockKeepAliveScheduler = EasyMock.createNiceMock(ScheduledExecutorService.class);
field = testClass.getClass().getDeclaredField("keepAliveScheduler");
field.setAccessible(true);
field.set(testClass, mockKeepAliveScheduler);
field = testClass.getClass().getDeclaredField("connectionsScheduler");
field.setAccessible(true);
mockConnectionsScheduler = EasyMock.createNiceMock(ExecutorService.class);
field.set(testClass, mockConnectionsScheduler);
mockConnectionHandles = EasyMock.createNiceMock(BoundedLinkedTransferQueue.class);
mockConnection = EasyMock.createNiceMock(ConnectionHandle.class);
mockLock = EasyMock.createNiceMock(Lock.class);
mockLogger = TestUtils.mockLogger(testClass.getClass());
makeThreadSafe(mockLogger, true);
mockDatabaseMetadata = EasyMock.createNiceMock(DatabaseMetaData.class);
mockResultSet = EasyMock.createNiceMock(MockResultSet.class);
mockLogger.error((String)anyObject(), anyObject());
expectLastCall().anyTimes();
reset(mockConfig, mockKeepAliveScheduler, mockConnectionsScheduler, mockPartition,
mockConnectionHandles, mockConnection, mockLock);
}
#location 29
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testCreatePool() throws SQLException, ClassNotFoundException, CloneNotSupportedException {
BoneCPConfig mockConfig = createNiceMock(BoneCPConfig.class);
expect(mockConfig.getPartitionCount()).andReturn(1).anyTimes();
expect(mockConfig.getMaxConnectionsPerPartition()).andReturn(1).anyTimes();
expect(mockConfig.getMinConnectionsPerPartition()).andReturn(1).anyTimes();
expect(mockConfig.getIdleConnectionTestPeriodInMinutes()).andReturn(100L).anyTimes();
expect(mockConfig.getUsername()).andReturn("somethingbad").anyTimes();
expect(mockConfig.getPassword()).andReturn("somethingbad").anyTimes();
expect(mockConfig.getJdbcUrl()).andReturn("invalid").anyTimes();
// expect(mockConfig.getReleaseHelperThreads()).andReturn(1).once().andReturn(0).anyTimes();
replay(mockConfig);
try{
testClass.createPool(mockConfig);
fail("Should throw an exception");
} catch (RuntimeException e){
// do nothing
}
verify(mockConfig);
reset(mockConfig);
Class.forName(DRIVER);
mockConfig = createNiceMock(BoneCPConfig.class);
expect(mockConfig.getPartitionCount()).andReturn(1).anyTimes();
expect(mockConfig.getMaxConnectionsPerPartition()).andReturn(1).anyTimes();
expect(mockConfig.getMinConnectionsPerPartition()).andReturn(1).anyTimes();
expect(mockConfig.getIdleConnectionTestPeriodInMinutes()).andReturn(100L).anyTimes();
expect(mockConfig.getUsername()).andReturn(USERNAME).anyTimes();
expect(mockConfig.getPassword()).andReturn(PASSWORD).anyTimes();
expect(mockConfig.getJdbcUrl()).andReturn(URL).anyTimes();
expect(mockConfig.isLazyInit()).andReturn(false).anyTimes();
expect(mockConfig.clone()).andReturn(mockConfig).anyTimes();
replay(mockConfig);
try{
testClass.createPool(mockConfig);
} catch (RuntimeException e){
fail("Should pass: ");
}
verify(mockConfig);
} | #vulnerable code
@Test
public void testCreatePool() throws SQLException, ClassNotFoundException {
BoneCPConfig mockConfig = createNiceMock(BoneCPConfig.class);
expect(mockConfig.getPartitionCount()).andReturn(1).anyTimes();
expect(mockConfig.getMaxConnectionsPerPartition()).andReturn(1).anyTimes();
expect(mockConfig.getMinConnectionsPerPartition()).andReturn(1).anyTimes();
expect(mockConfig.getIdleConnectionTestPeriodInMinutes()).andReturn(100L).anyTimes();
expect(mockConfig.getUsername()).andReturn("somethingbad").anyTimes();
expect(mockConfig.getPassword()).andReturn("somethingbad").anyTimes();
expect(mockConfig.getJdbcUrl()).andReturn("invalid").anyTimes();
// expect(mockConfig.getReleaseHelperThreads()).andReturn(1).once().andReturn(0).anyTimes();
replay(mockConfig);
try{
testClass.createPool(mockConfig);
fail("Should throw an exception");
} catch (RuntimeException e){
// do nothing
}
verify(mockConfig);
reset(mockConfig);
Class.forName(DRIVER);
mockConfig = createNiceMock(BoneCPConfig.class);
expect(mockConfig.getPartitionCount()).andReturn(1).anyTimes();
expect(mockConfig.getMaxConnectionsPerPartition()).andReturn(1).anyTimes();
expect(mockConfig.getMinConnectionsPerPartition()).andReturn(1).anyTimes();
expect(mockConfig.getIdleConnectionTestPeriodInMinutes()).andReturn(100L).anyTimes();
expect(mockConfig.getUsername()).andReturn(USERNAME).anyTimes();
expect(mockConfig.getPassword()).andReturn(PASSWORD).anyTimes();
expect(mockConfig.getJdbcUrl()).andReturn(URL).anyTimes();
replay(mockConfig);
try{
testClass.createPool(mockConfig);
} catch (RuntimeException e){
fail("Should pass");
}
verify(mockConfig);
}
#location 15
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testCreatePool() throws SQLException, ClassNotFoundException, CloneNotSupportedException {
BoneCPConfig mockConfig = createNiceMock(BoneCPConfig.class);
expect(mockConfig.getPartitionCount()).andReturn(1).anyTimes();
expect(mockConfig.getMaxConnectionsPerPartition()).andReturn(1).anyTimes();
expect(mockConfig.getMinConnectionsPerPartition()).andReturn(1).anyTimes();
expect(mockConfig.getIdleConnectionTestPeriodInMinutes()).andReturn(100L).anyTimes();
expect(mockConfig.getUsername()).andReturn("somethingbad").anyTimes();
expect(mockConfig.getPassword()).andReturn("somethingbad").anyTimes();
expect(mockConfig.getJdbcUrl()).andReturn("invalid").anyTimes();
// expect(mockConfig.getReleaseHelperThreads()).andReturn(1).once().andReturn(0).anyTimes();
replay(mockConfig);
try{
testClass.createPool(mockConfig);
fail("Should throw an exception");
} catch (RuntimeException e){
// do nothing
}
verify(mockConfig);
reset(mockConfig);
Class.forName(DRIVER);
mockConfig = createNiceMock(BoneCPConfig.class);
expect(mockConfig.getPartitionCount()).andReturn(1).anyTimes();
expect(mockConfig.getMaxConnectionsPerPartition()).andReturn(1).anyTimes();
expect(mockConfig.getMinConnectionsPerPartition()).andReturn(1).anyTimes();
expect(mockConfig.getIdleConnectionTestPeriodInMinutes()).andReturn(100L).anyTimes();
expect(mockConfig.getUsername()).andReturn(USERNAME).anyTimes();
expect(mockConfig.getPassword()).andReturn(PASSWORD).anyTimes();
expect(mockConfig.getJdbcUrl()).andReturn(URL).anyTimes();
expect(mockConfig.isLazyInit()).andReturn(false).anyTimes();
expect(mockConfig.clone()).andReturn(mockConfig).anyTimes();
replay(mockConfig);
try{
testClass.createPool(mockConfig);
} catch (RuntimeException e){
fail("Should pass: ");
}
verify(mockConfig);
} | #vulnerable code
@Test
public void testCreatePool() throws SQLException, ClassNotFoundException {
BoneCPConfig mockConfig = createNiceMock(BoneCPConfig.class);
expect(mockConfig.getPartitionCount()).andReturn(1).anyTimes();
expect(mockConfig.getMaxConnectionsPerPartition()).andReturn(1).anyTimes();
expect(mockConfig.getMinConnectionsPerPartition()).andReturn(1).anyTimes();
expect(mockConfig.getIdleConnectionTestPeriodInMinutes()).andReturn(100L).anyTimes();
expect(mockConfig.getUsername()).andReturn("somethingbad").anyTimes();
expect(mockConfig.getPassword()).andReturn("somethingbad").anyTimes();
expect(mockConfig.getJdbcUrl()).andReturn("invalid").anyTimes();
// expect(mockConfig.getReleaseHelperThreads()).andReturn(1).once().andReturn(0).anyTimes();
replay(mockConfig);
try{
testClass.createPool(mockConfig);
fail("Should throw an exception");
} catch (RuntimeException e){
// do nothing
}
verify(mockConfig);
reset(mockConfig);
Class.forName(DRIVER);
mockConfig = createNiceMock(BoneCPConfig.class);
expect(mockConfig.getPartitionCount()).andReturn(1).anyTimes();
expect(mockConfig.getMaxConnectionsPerPartition()).andReturn(1).anyTimes();
expect(mockConfig.getMinConnectionsPerPartition()).andReturn(1).anyTimes();
expect(mockConfig.getIdleConnectionTestPeriodInMinutes()).andReturn(100L).anyTimes();
expect(mockConfig.getUsername()).andReturn(USERNAME).anyTimes();
expect(mockConfig.getPassword()).andReturn(PASSWORD).anyTimes();
expect(mockConfig.getJdbcUrl()).andReturn(URL).anyTimes();
replay(mockConfig);
try{
testClass.createPool(mockConfig);
} catch (RuntimeException e){
fail("Should pass");
}
verify(mockConfig);
}
#location 15
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void initializer_same_key() {
App app = new App(AppConfig.builder().signingSecret("secret").build());
final AtomicBoolean called = new AtomicBoolean(false);
assertThat(called.get(), is(false));
app.initializer("foo", (theApp) -> {
called.set(true);
});
app.initializer("foo", (theApp) -> {
});
app.initialize();
assertThat(called.get(), is(false));
} | #vulnerable code
@Test
public void initializer_same_key() {
App app = new App();
final AtomicBoolean called = new AtomicBoolean(false);
assertThat(called.get(), is(false));
app.initializer("foo", (theApp) -> {
called.set(true);
});
app.initializer("foo", (theApp) -> {
});
app.initialize();
assertThat(called.get(), is(false));
}
#location 12
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public Request<?> toSlackRequest(HttpRequest<?> req, LinkedHashMap<String, String> body) {
String requestBody = body.entrySet().stream().map(e -> {
try {
String k = URLEncoder.encode(e.getKey(), "UTF-8");
String v = URLEncoder.encode(e.getValue(), "UTF-8");
return k + "=" + v;
} catch (UnsupportedEncodingException ex) {
return e.getKey() + "=" + e.getValue();
}
}).collect(Collectors.joining("&"));
RequestHeaders headers = new RequestHeaders(req.getHeaders().asMap());
SlackRequestParser.HttpRequest rawRequest = SlackRequestParser.HttpRequest.builder()
.requestUri(req.getPath())
.queryString(flatten(req.getParameters().asMap()))
.headers(headers)
.requestBody(requestBody)
.remoteAddress(toString(req.getRemoteAddress().getAddress().getAddress()))
.build();
return requestParser.parse(rawRequest);
} | #vulnerable code
public Request<?> toSlackRequest(HttpRequest<?> req, LinkedHashMap<String, String> body) {
String requestBody = body.entrySet().stream().map(e -> {
try {
String k = URLEncoder.encode(e.getKey(), "UTF-8");
String v = URLEncoder.encode(e.getValue(), "UTF-8");
return k + "=" + v;
} catch (UnsupportedEncodingException ex) {
return e.getKey() + "=" + e.getValue();
}
}).collect(Collectors.joining("&"));
RequestHeaders headers = new RequestHeaders(flatten(req.getHeaders().asMap()));
SlackRequestParser.HttpRequest rawRequest = SlackRequestParser.HttpRequest.builder()
.requestUri(req.getPath())
.queryString(flatten(req.getParameters().asMap()))
.headers(headers)
.requestBody(requestBody)
.remoteAddress(toString(req.getRemoteAddress().getAddress().getAddress()))
.build();
return requestParser.parse(rawRequest);
}
#location 11
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void rtmStart() throws Exception {
// TODO: "prefs" support
SlackConfig config = new SlackConfig();
config.setLibraryMaintainerMode(false);
config.getHttpClientResponseHandlers().add(new JsonDataRecordingListener());
Slack slack = Slack.getInstance(config);
String channelName = "test" + System.currentTimeMillis();
TestChannelGenerator channelGenerator = new TestChannelGenerator(testConfig, channelCreationToken);
Conversation channel = channelGenerator.createNewPublicChannel(channelName);
try {
String channelId = channel.getId();
// need to invite the bot user to the created channel before starting an RTM session
inviteBotUser(channelId);
Thread.sleep(3000);
try (RTMClient rtm = slack.rtmStart(classicAppBotToken)) {
User user = rtm.getConnectedBotUser();
assertThat(user.getId(), is(notNullValue()));
assertThat(user.getTeamId(), is(notNullValue()));
assertThat(user.getName(), is(notNullValue()));
assertThat(user.getProfile(), is(notNullValue()));
assertThat(user.getProfile().getBotId(), is(notNullValue()));
verifyRTMClientBehavior(channelId, rtm);
}
} finally {
channelGenerator.archiveChannel(channel);
}
} | #vulnerable code
@Test
public void rtmStart() throws Exception {
// TODO: "prefs" support
SlackConfig config = new SlackConfig();
config.setLibraryMaintainerMode(false);
config.getHttpClientResponseHandlers().add(new JsonDataRecordingListener());
Slack slack = Slack.getInstance(config);
String channelName = "test" + System.currentTimeMillis();
TestChannelGenerator channelGenerator = new TestChannelGenerator(testConfig, channelCreationToken);
Conversation channel = channelGenerator.createNewPublicChannel(channelName);
try {
String channelId = channel.getId();
// need to invite the bot user to the created channel before starting an RTM session
inviteBotUser(channelId);
Thread.sleep(3000);
try (RTMClient rtm = slack.rtmStart(botToken)) {
User user = rtm.getConnectedBotUser();
assertThat(user.getId(), is(notNullValue()));
assertThat(user.getTeamId(), is(notNullValue()));
assertThat(user.getName(), is(notNullValue()));
assertThat(user.getProfile(), is(notNullValue()));
assertThat(user.getProfile().getBotId(), is(notNullValue()));
verifyRTMClientBehavior(channelId, rtm);
}
} finally {
channelGenerator.archiveChannel(channel);
}
}
#location 32
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public Bot findBot(String enterpriseId, String teamId) {
AmazonS3 s3 = this.createS3Client();
String fullKey = getBotKey(enterpriseId, teamId);
if (isHistoricalDataEnabled()) {
fullKey = fullKey + "-latest";
}
if (getObjectMetadata(s3, fullKey) == null && enterpriseId != null) {
String nonGridKey = getBotKey(null, teamId);
if (isHistoricalDataEnabled()) {
nonGridKey = nonGridKey + "-latest";
}
S3Object nonGridObject = getObject(s3, nonGridKey);
if (nonGridObject != null) {
try {
Bot bot = toBot(nonGridObject);
bot.setEnterpriseId(enterpriseId); // the workspace seems to be in a Grid org now
save(s3, fullKey, JsonOps.toJsonString(bot), "AWS S3 putObject result of Bot data - {}");
return bot;
} catch (Exception e) {
log.error("Failed to save a new Bot data for enterprise_id: {}, team_id: {}", enterpriseId, teamId);
}
}
}
S3Object s3Object = getObject(s3, fullKey);
try {
return toBot(s3Object);
} catch (IOException e) {
log.error("Failed to load Bot data for enterprise_id: {}, team_id: {}", enterpriseId, teamId);
return null;
}
} | #vulnerable code
@Override
public Bot findBot(String enterpriseId, String teamId) {
AmazonS3 s3 = this.createS3Client();
String fullKey = getBotKey(enterpriseId, teamId);
if (isHistoricalDataEnabled()) {
fullKey = fullKey + "-latest";
}
if (s3.getObjectMetadata(bucketName, fullKey) == null && enterpriseId != null) {
String nonGridKey = getBotKey(null, teamId);
if (isHistoricalDataEnabled()) {
nonGridKey = nonGridKey + "-latest";
}
S3Object nonGridObject = s3.getObject(bucketName, nonGridKey);
if (nonGridObject != null) {
try {
Bot bot = toBot(nonGridObject);
bot.setEnterpriseId(enterpriseId); // the workspace seems to be in a Grid org now
save(s3, fullKey, JsonOps.toJsonString(bot), "AWS S3 putObject result of Bot data - {}");
return bot;
} catch (Exception e) {
log.error("Failed to save a new Bot data for enterprise_id: {}, team_id: {}", enterpriseId, teamId);
}
}
}
S3Object s3Object = s3.getObject(bucketName, fullKey);
try {
return toBot(s3Object);
} catch (IOException e) {
log.error("Failed to load Bot data for enterprise_id: {}, team_id: {}", enterpriseId, teamId);
return null;
}
}
#location 27
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void initializer_start() {
App app = new App(AppConfig.builder().signingSecret("secret").build());
final AtomicBoolean called = new AtomicBoolean(false);
assertThat(called.get(), is(false));
app.initializer("foo", (theApp) -> {
called.set(true);
});
app.start();
assertThat(called.get(), is(true));
} | #vulnerable code
@Test
public void initializer_start() {
App app = new App();
final AtomicBoolean called = new AtomicBoolean(false);
assertThat(called.get(), is(false));
app.initializer("foo", (theApp) -> {
called.set(true);
});
app.start();
assertThat(called.get(), is(true));
}
#location 10
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void rtmStart() throws Exception {
// TODO: "prefs" support
SlackConfig config = new SlackConfig();
config.setLibraryMaintainerMode(false);
config.getHttpClientResponseHandlers().add(new JsonDataRecordingListener());
Slack slack = Slack.getInstance(config);
String channelName = "test" + System.currentTimeMillis();
TestChannelGenerator channelGenerator = new TestChannelGenerator(testConfig, channelCreationToken);
Conversation channel = channelGenerator.createNewPublicChannel(channelName);
try {
String channelId = channel.getId();
// need to invite the bot user to the created channel before starting an RTM session
inviteBotUser(channelId);
Thread.sleep(3000);
try (RTMClient rtm = slack.rtmStart(classicAppBotToken)) {
User user = rtm.getConnectedBotUser();
assertThat(user.getId(), is(notNullValue()));
assertThat(user.getTeamId(), is(notNullValue()));
assertThat(user.getName(), is(notNullValue()));
assertThat(user.getProfile(), is(notNullValue()));
assertThat(user.getProfile().getBotId(), is(notNullValue()));
verifyRTMClientBehavior(channelId, rtm);
}
} finally {
channelGenerator.archiveChannel(channel);
}
} | #vulnerable code
@Test
public void rtmStart() throws Exception {
// TODO: "prefs" support
SlackConfig config = new SlackConfig();
config.setLibraryMaintainerMode(false);
config.getHttpClientResponseHandlers().add(new JsonDataRecordingListener());
Slack slack = Slack.getInstance(config);
String channelName = "test" + System.currentTimeMillis();
TestChannelGenerator channelGenerator = new TestChannelGenerator(testConfig, channelCreationToken);
Conversation channel = channelGenerator.createNewPublicChannel(channelName);
try {
String channelId = channel.getId();
// need to invite the bot user to the created channel before starting an RTM session
inviteBotUser(channelId);
Thread.sleep(3000);
try (RTMClient rtm = slack.rtmStart(botToken)) {
User user = rtm.getConnectedBotUser();
assertThat(user.getId(), is(notNullValue()));
assertThat(user.getTeamId(), is(notNullValue()));
assertThat(user.getName(), is(notNullValue()));
assertThat(user.getProfile(), is(notNullValue()));
assertThat(user.getProfile().getBotId(), is(notNullValue()));
verifyRTMClientBehavior(channelId, rtm);
}
} finally {
channelGenerator.archiveChannel(channel);
}
}
#location 20
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void initializer_called() {
App app = new App(AppConfig.builder().signingSecret("secret").build());
final AtomicBoolean called = new AtomicBoolean(false);
assertThat(called.get(), is(false));
app.initializer("foo", (theApp) -> {
called.set(true);
});
app.initialize();
assertThat(called.get(), is(true));
} | #vulnerable code
@Test
public void initializer_called() {
App app = new App();
final AtomicBoolean called = new AtomicBoolean(false);
assertThat(called.get(), is(false));
app.initializer("foo", (theApp) -> {
called.set(true);
});
app.initialize();
assertThat(called.get(), is(true));
}
#location 10
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void test() throws Exception {
String channelName = "test" + System.currentTimeMillis();
TestChannelGenerator channelGenerator = new TestChannelGenerator(testConfig, channelCreationToken);
Conversation channel = channelGenerator.createNewPublicChannel(channelName);
try {
String channelId = channel.getId();
// need to invite the bot user to the created channel before starting an RTM session
inviteBotUser(channelId);
RTMEventsDispatcher dispatcher = RTMEventsDispatcherFactory.getInstance();
HelloHandler hello = new HelloHandler();
dispatcher.register(hello);
SubHelloHandler hello2 = new SubHelloHandler();
dispatcher.register(hello2);
dispatcher.register(new UserTypingHandler());
SlackTestConfig testConfig = SlackTestConfig.getInstance();
Slack slack = Slack.getInstance(testConfig.getConfig());
try (RTMClient rtm = slack.rtmConnect(classicAppBotToken)) {
rtm.addMessageHandler(dispatcher.toMessageHandler());
rtm.connect();
Thread.sleep(1000L);
assertThat(hello.counter.get(), is(1));
assertThat(hello2.counter.get(), is(1));
BotMessageHandler bot = new BotMessageHandler();
dispatcher.register(bot);
ChatPostMessageResponse chatPostMessage = slack.methods(classicAppBotToken)
.chatPostMessage(r -> r.channel(channelId).text("Hi!"));
assertThat(chatPostMessage.getError(), is(nullValue()));
Thread.sleep(1000L);
assertThat(bot.counter.get(), is(1));
rtm.reconnect();
Thread.sleep(1000L);
assertThat(hello.counter.get(), is(2));
assertThat(hello2.counter.get(), is(2));
dispatcher.deregister(hello);
rtm.reconnect();
Thread.sleep(1000L);
assertThat(hello.counter.get(), is(2)); // should not be incremented
assertThat(hello2.counter.get(), is(3));
}
} finally {
channelGenerator.archiveChannel(channel);
}
} | #vulnerable code
@Test
public void test() throws Exception {
String channelName = "test" + System.currentTimeMillis();
TestChannelGenerator channelGenerator = new TestChannelGenerator(testConfig, channelCreationToken);
Conversation channel = channelGenerator.createNewPublicChannel(channelName);
try {
String channelId = channel.getId();
// need to invite the bot user to the created channel before starting an RTM session
inviteBotUser(channelId);
RTMEventsDispatcher dispatcher = RTMEventsDispatcherFactory.getInstance();
HelloHandler hello = new HelloHandler();
dispatcher.register(hello);
SubHelloHandler hello2 = new SubHelloHandler();
dispatcher.register(hello2);
dispatcher.register(new UserTypingHandler());
SlackTestConfig testConfig = SlackTestConfig.getInstance();
Slack slack = Slack.getInstance(testConfig.getConfig());
try (RTMClient rtm = slack.rtmConnect(classicAppBotToken)) {
rtm.addMessageHandler(dispatcher.toMessageHandler());
rtm.connect();
Thread.sleep(1000L);
assertThat(hello.counter.get(), is(1));
assertThat(hello2.counter.get(), is(1));
rtm.reconnect();
Thread.sleep(1000L);
assertThat(hello.counter.get(), is(2));
assertThat(hello2.counter.get(), is(2));
dispatcher.deregister(hello);
rtm.reconnect();
Thread.sleep(1000L);
assertThat(hello.counter.get(), is(2)); // should not be incremented
assertThat(hello2.counter.get(), is(3));
}
} finally {
channelGenerator.archiveChannel(channel);
}
}
#location 24
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void status() {
App app = new App(AppConfig.builder().signingSecret("secret").build());
assertThat(app.status(), is(App.Status.Stopped));
app.start();
assertThat(app.status(), is(App.Status.Running));
app.stop();
assertThat(app.status(), is(App.Status.Stopped));
app.start();
assertThat(app.status(), is(App.Status.Running));
app.stop();
assertThat(app.status(), is(App.Status.Stopped));
app.start();
app.start();
assertThat(app.status(), is(App.Status.Running));
} | #vulnerable code
@Test
public void status() {
App app = new App();
assertThat(app.status(), is(App.Status.Stopped));
app.start();
assertThat(app.status(), is(App.Status.Running));
app.stop();
assertThat(app.status(), is(App.Status.Stopped));
app.start();
assertThat(app.status(), is(App.Status.Running));
app.stop();
assertThat(app.status(), is(App.Status.Stopped));
app.start();
app.start();
assertThat(app.status(), is(App.Status.Running));
}
#location 6
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void builder_config() {
App app = new App(AppConfig.builder().signingSecret("secret").build());
assertNotNull(app.config());
app = app.toBuilder().build();
assertNotNull(app.config());
app = app.toOAuthCallbackApp();
assertNotNull(app.config());
app = app.toOAuthStartApp();
assertNotNull(app.config());
} | #vulnerable code
@Test
public void builder_config() {
App app = new App();
assertNotNull(app.config());
app = app.toBuilder().build();
assertNotNull(app.config());
app = app.toOAuthCallbackApp();
assertNotNull(app.config());
app = app.toOAuthStartApp();
assertNotNull(app.config());
}
#location 4
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
protected Request<?> toSlackRequest(ApiGatewayRequest awsReq) {
if (log.isDebugEnabled()) {
log.debug("AWS API Gateway Request: {}", awsReq);
}
RequestContext context = awsReq.getRequestContext();
SlackRequestParser.HttpRequest rawRequest = SlackRequestParser.HttpRequest.builder()
.requestUri(awsReq.getPath())
.queryString(toStringToStringListMap(awsReq.getQueryStringParameters()))
.headers(new RequestHeaders(toStringToStringListMap(awsReq.getHeaders())))
.requestBody(awsReq.getBody())
.remoteAddress(context != null && context.getIdentity() != null ? context.getIdentity().getSourceIp() : null)
.build();
return requestParser.parse(rawRequest);
} | #vulnerable code
protected Request<?> toSlackRequest(ApiGatewayRequest awsReq) {
if (log.isDebugEnabled()) {
log.debug("AWS API Gateway Request: {}", awsReq);
}
SlackRequestParser.HttpRequest rawRequest = SlackRequestParser.HttpRequest.builder()
.requestUri(awsReq.getPath())
.queryString(toStringToStringListMap(awsReq.getQueryStringParameters()))
.headers(new RequestHeaders(toStringToStringListMap(awsReq.getHeaders())))
.requestBody(awsReq.getBody())
.remoteAddress(awsReq.getRequestContext().getIdentity() != null ? awsReq.getRequestContext().getIdentity().getSourceIp() : null)
.build();
return requestParser.parse(rawRequest);
}
#location 8
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void builder_status() {
App app = new App(AppConfig.builder().signingSecret("secret").build());
assertNotNull(app.status());
assertThat(app.status(), is(App.Status.Stopped));
app = app.toBuilder().build();
assertThat(app.status(), is(App.Status.Stopped));
app = app.toOAuthCallbackApp();
assertThat(app.status(), is(App.Status.Stopped));
app = app.toOAuthStartApp();
assertThat(app.status(), is(App.Status.Stopped));
} | #vulnerable code
@Test
public void builder_status() {
App app = new App();
assertNotNull(app.status());
assertThat(app.status(), is(App.Status.Stopped));
app = app.toBuilder().build();
assertThat(app.status(), is(App.Status.Stopped));
app = app.toOAuthCallbackApp();
assertThat(app.status(), is(App.Status.Stopped));
app = app.toOAuthStartApp();
assertThat(app.status(), is(App.Status.Stopped));
}
#location 5
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public Installer findInstaller(String enterpriseId, String teamId, String userId) {
AmazonS3 s3 = this.createS3Client();
String fullKey = getInstallerKey(enterpriseId, teamId, userId);
if (isHistoricalDataEnabled()) {
fullKey = fullKey + "-latest";
}
if (getObjectMetadata(s3, fullKey) == null && enterpriseId != null) {
String nonGridKey = getInstallerKey(null, teamId, userId);
if (isHistoricalDataEnabled()) {
nonGridKey = nonGridKey + "-latest";
}
S3Object nonGridObject = getObject(s3, nonGridKey);
if (nonGridObject != null) {
try {
Installer installer = toInstaller(nonGridObject);
installer.setEnterpriseId(enterpriseId); // the workspace seems to be in a Grid org now
saveInstallerAndBot(installer);
return installer;
} catch (Exception e) {
log.error("Failed to save a new Installer data for enterprise_id: {}, team_id: {}, user_id: {}",
enterpriseId, teamId, userId);
}
}
}
S3Object s3Object = getObject(s3, fullKey);
try {
return toInstaller(s3Object);
} catch (Exception e) {
log.error("Failed to save a new Installer data for enterprise_id: {}, team_id: {}, user_id: {}",
enterpriseId, teamId, userId);
return null;
}
} | #vulnerable code
@Override
public Installer findInstaller(String enterpriseId, String teamId, String userId) {
AmazonS3 s3 = this.createS3Client();
String fullKey = getInstallerKey(enterpriseId, teamId, userId);
if (isHistoricalDataEnabled()) {
fullKey = fullKey + "-latest";
}
if (s3.getObjectMetadata(bucketName, fullKey) == null && enterpriseId != null) {
String nonGridKey = getInstallerKey(null, teamId, userId);
if (isHistoricalDataEnabled()) {
nonGridKey = nonGridKey + "-latest";
}
S3Object nonGridObject = s3.getObject(bucketName, nonGridKey);
if (nonGridObject != null) {
try {
Installer installer = toInstaller(nonGridObject);
installer.setEnterpriseId(enterpriseId); // the workspace seems to be in a Grid org now
saveInstallerAndBot(installer);
return installer;
} catch (Exception e) {
log.error("Failed to save a new Installer data for enterprise_id: {}, team_id: {}, user_id: {}",
enterpriseId, teamId, userId);
}
}
}
S3Object s3Object = s3.getObject(bucketName, fullKey);
try {
return toInstaller(s3Object);
} catch (Exception e) {
log.error("Failed to save a new Installer data for enterprise_id: {}, team_id: {}, user_id: {}",
enterpriseId, teamId, userId);
return null;
}
}
#location 28
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static void main(String[] args) throws Exception {
test();
} | #vulnerable code
public static void main(String[] args) throws Exception {
DebugProtocol protocol = new DebugProtocol(new EventListener() {
@Override
public void onPageLoad() {
//To change body of implemented methods use File | Settings | File Templates.
}
@Override
public void domHasChanged(Event event) {
//To change body of implemented methods use File | Settings | File Templates.
}
@Override
public void frameDied(JSONObject message) {
//To change body of implemented methods use File | Settings | File Templates.
}
}, "com.apple.mobilesafari");
System.out.println(protocol.sendCommand(DOM.getDocument()).toString(2));
}
#location 2
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void canSwitchToTheWebViewAndFindByCSS() throws Exception {
IOSCapabilities safari = IOSCapabilities.iphone("UICatalog");
safari.setCapability(IOSCapabilities.TIME_HACK, false);
RemoteUIADriver driver = null;
try {
driver = new RemoteUIADriver(getRemoteURL(), SampleApps.uiCatalogCap());
Set<String> handles = driver.getWindowHandles();
Assert.assertEquals(handles.size(), 1);
UIAElement webCell = driver.findElement(new AndCriteria(new TypeCriteria(UIATableCell.class), new NameCriteria(
"Web", MatchingStrategy.starts)));
webCell.tap();
handles = driver.getWindowHandles();
Assert.assertEquals(handles.size(), 2);
driver.switchTo().window("Web");
final By by = By.cssSelector("a[href='http://store.apple.com/']");
new WebDriverWait(driver, 5).until(new ExpectedCondition<WebElement>() {
@Override
public WebElement apply(WebDriver d) {
return d.findElement(by);
}
});
WebElement el = driver.findElement(by);
Assert.assertEquals(el.getAttribute("href"), "http://store.apple.com/");
} finally {
driver.quit();
}
} | #vulnerable code
@Test
public void canSwitchToTheWebViewAndFindByCSS() throws Exception {
IOSCapabilities safari = IOSCapabilities.iphone("UICatalog");
safari.setCapability(IOSCapabilities.TIME_HACK, false);
RemoteUIADriver driver = null;
try {
driver = new RemoteUIADriver(getRemoteURL(), SampleApps.uiCatalogCap());
Set<String> handles = driver.getWindowHandles();
Assert.assertEquals(handles.size(), 1);
UIAElement el = driver.findElement(new AndCriteria(new TypeCriteria(UIATableCell.class), new NameCriteria("Web",
MatchingStrategy.starts)));
el.tap();
handles = driver.getWindowHandles();
Assert.assertEquals(handles.size(), 2);
UIAElement back = driver
.findElement(new AndCriteria(new TypeCriteria(UIAButton.class), new NameCriteria("Back")));
back.tap();
handles = driver.getWindowHandles();
Assert.assertEquals(handles.size(), 1);
} finally {
driver.quit();
}
}
#location 14
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public View handle(HttpServletRequest req) throws IOSAutomationException {
String path = req.getPathInfo();
String pattern = "/resources/";
int end = path.indexOf(pattern) + pattern.length();
String resource = path.substring(end);
InputStream is = null;
if (resource.endsWith("lastScreen.png")) {
//is = getModel().getLastScreenshotInputStream();
} else {
is = IDEServlet.class.getResourceAsStream("/" + resource);
}
String mime = getMimeType(resource);
if (is == null) {
throw new IOSAutomationException("error getting resource " + req.getPathInfo()
+ req.getQueryString());
}
return new ResourceView(is, mime);
} | #vulnerable code
public View handle(HttpServletRequest req) throws IOSAutomationException {
String path = req.getPathInfo();
String pattern = "/resources/";
int end = path.indexOf(pattern) + pattern.length();
String resource = path.substring(end);
InputStream is = null;
if (resource.endsWith("lastScreen.png")) {
is = getModel().getLastScreenshotInputStream();
} else {
is = IDEServlet.class.getResourceAsStream("/" + resource);
}
String mime = getMimeType(resource);
if (is == null) {
throw new IOSAutomationException("error getting resource " + req.getPathInfo()
+ req.getQueryString());
}
return new ResourceView(is, mime);
}
#location 19
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public Response handle() throws Exception {
waitForPageToLoad();
int implicitWait = (Integer) getConf("implicit_wait", 0);
long deadline = System.currentTimeMillis() + implicitWait;
List<RemoteWebElement> elements = null;
do {
try {
elements = findElements();
if (elements.size() != 0) {
break;
}
} catch (NoSuchElementException e) {
//ignore.
} catch (RemoteExceptionException e2) {
// ignore.
// if the page is reloading, the previous nodeId won't be there anymore, resulting in a
// RemoteExceptionException: Could not find node with given id.Keep looking.
}
} while (System.currentTimeMillis() < deadline);
JSONArray array = new JSONArray();
List<JSONObject> list = new ArrayList<JSONObject>();
for (RemoteWebElement el : elements) {
list.add(new JSONObject().put("ELEMENT", "" + el.getNodeId().getId()));
}
Response resp = new Response();
resp.setSessionId(getSession().getSessionId());
resp.setStatus(0);
resp.setValue(list);
return resp;
} | #vulnerable code
@Override
public Response handle() throws Exception {
JSONObject payload = getRequest().getPayload();
String type = payload.getString("using");
String value = payload.getString("value");
RemoteWebElement element = null;
if (getRequest().hasVariable(":reference")) {
int id = Integer.parseInt(getRequest().getVariableValue(":reference"));
element = new RemoteWebElement(new NodeId(id), getSession());
} else {
element = getSession().getWebInspector().getDocument();
}
List<RemoteWebElement> res;
if ("link text".equals(type)) {
res = element.findElementsByLinkText(value, false);
} else if ("partial link text".equals(type)) {
res = element.findElementsByLinkText(value, true);
} else if ("xpath".equals(type)) {
res = element.findElementsByXpath(value);
} else {
String cssSelector = ToCSSSelectorConvertor.convertToCSSSelector(type, value);
res = element.findElementsByCSSSelector(cssSelector);
}
JSONArray array = new JSONArray();
List<JSONObject> list = new ArrayList<JSONObject>();
for (RemoteWebElement el : res) {
list.add(new JSONObject().put("ELEMENT", "" + el.getNodeId().getId()));
}
Response resp = new Response();
resp.setSessionId(getSession().getSessionId());
resp.setStatus(0);
resp.setValue(list);
return resp;
}
#location 13
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public Set<String> getWindowHandles() {
WebDriverLikeRequest request = buildRequest(WebDriverLikeCommand.WINDOW_HANDLES);
List<String> all = execute(request);
Set<String> res = new HashSet<String>();
res.addAll(all);
return res;
} | #vulnerable code
@Override
public Set<String> getWindowHandles() {
try {
JSONObject payload = new JSONObject();
WebDriverLikeCommand command = WebDriverLikeCommand.WINDOW_HANDLES;
Path p = new Path(command).withSession(getSessionId());
WebDriverLikeRequest request = new WebDriverLikeRequest(command.method(), p, payload);
Response response = execute(request);
JSONArray array = ((JSONArray) response.getValue());
Set<String> handles = new HashSet<String>();
for (int i = 0; i < array.length(); i++) {
handles.add(array.getString(i));
}
return handles;
} catch (IOSAutomationException e) {
throw e;
} catch (Exception e) {
throw new IOSAutomationException("bug", e);
}
}
#location 11
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public Response handle() throws Exception {
waitForPageToLoad();
int implicitWait = (Integer) getConf("implicit_wait", 0);
long deadline = System.currentTimeMillis() + implicitWait;
RemoteWebElement rwe = null;
do {
try {
rwe = findElement();
break;
} catch (NoSuchElementException e) {
//ignore.
} catch (RemoteExceptionException e2) {
// ignore.
// if the page is reloading, the previous nodeId won't be there anymore, resulting in a
// RemoteExceptionException: Could not find node with given id.Keep looking.
}
} while (System.currentTimeMillis() < deadline);
if (rwe == null) {
throw new NoSuchElementException(
"No element found for " + getRequest().getPayload() + " after waiting for " + implicitWait
+ " ms.");
} else {
JSONObject res = new JSONObject();
res.put("ELEMENT", "" + rwe.getNodeId().getId());
Response resp = new Response();
resp.setSessionId(getSession().getSessionId());
resp.setStatus(0);
resp.setValue(res);
return resp;
}
} | #vulnerable code
@Override
public Response handle() throws Exception {
JSONObject payload = getRequest().getPayload();
String type = payload.getString("using");
String value = payload.getString("value");
RemoteWebElement element = null;
if (getRequest().hasVariable(":reference")) {
int id = Integer.parseInt(getRequest().getVariableValue(":reference"));
element = new RemoteWebElement(new NodeId(id), getSession());
} else {
element = getSession().getWebInspector().getDocument();
}
RemoteWebElement rwe;
if ("link text".equals(type)) {
rwe = element.findElementByLinkText(value, false);
} else if ("partial link text".equals(type)) {
rwe = element.findElementByLinkText(value, true);
} else if ("xpath".equals(type)) {
rwe = element.findElementByXpath(value);
} else {
String cssSelector = ToCSSSelectorConvertor.convertToCSSSelector(type, value);
rwe = element.findElementByCSSSelector(cssSelector);
}
JSONObject res = new JSONObject();
if (rwe == null) {
throw new NoSuchElementException("No element found for " + type + "=" + value);
} else {
res.put("ELEMENT", "" + rwe.getNodeId().getId());
Response resp = new Response();
resp.setSessionId(getSession().getSessionId());
resp.setStatus(0);
resp.setValue(res);
return resp;
}
}
#location 13
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void onPageLoad() {
System.err.println("new page loaded");
pageLoaded = true;
reset();
try {
Thread.sleep(5000);
System.out.println(
"on page load:" + session.getWebInspector().getProtocol().sendCommand(DOM.getDocument())
.optJSONObject("root").optString("documentURL"));
} catch (Exception e) {
e.printStackTrace();
}
} | #vulnerable code
@Override
public void onPageLoad() {
System.err.println("new page loaded");
pageLoaded = true;
reset();
}
#location 5
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void onPageLoad() {
pageLoaded = true;
reset();
} | #vulnerable code
@Override
public void onPageLoad() {
System.err.println("new page loaded");
pageLoaded = true;
reset();
try {
Thread.sleep(5000);
System.out.println(
"on page load:" + session.getWebInspector().getProtocol().sendCommand(DOM.getDocument())
.optJSONObject("root").optString("documentURL"));
} catch (Exception e) {
e.printStackTrace();
}
}
#location 9
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void onPageLoad() {
pageLoaded = true;
reset();
} | #vulnerable code
@Override
public void onPageLoad() {
System.err.println("new page loaded");
pageLoaded = true;
reset();
try {
Thread.sleep(5000);
System.out.println(
"on page load:" + session.getWebInspector().getProtocol().sendCommand(DOM.getDocument())
.optJSONObject("root").optString("documentURL"));
} catch (Exception e) {
e.printStackTrace();
}
}
#location 5
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void onPageLoad() {
pageLoaded = true;
reset();
} | #vulnerable code
@Override
public void onPageLoad() {
System.err.println("new page loaded");
pageLoaded = true;
reset();
try {
Thread.sleep(5000);
System.out.println(
"on page load:" + session.getWebInspector().getProtocol().sendCommand(DOM.getDocument())
.optJSONObject("root").optString("documentURL"));
} catch (Exception e) {
e.printStackTrace();
}
}
#location 9
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static void persist(File screenshot, JSONObject tree, File dest) throws FileNotFoundException, IOException,
JSONException {
IOUtils.copy(new StringReader(tree.toString(2)), new FileOutputStream(dest), "UTF-8");
} | #vulnerable code
public static void persist(File screenshot, JSONObject tree, File dest)
throws FileNotFoundException, IOException, JSONException {
System.out.println(screenshot.getAbsolutePath());
FileWriter write = new FileWriter(dest);
IOUtils.copy(new StringReader(tree.toString(2)), new FileOutputStream(dest), "UTF-8");
System.out.println(dest.getAbsolutePath());
}
#location 4
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void onPageLoad() {
pageLoaded = true;
reset();
} | #vulnerable code
@Override
public void onPageLoad() {
System.err.println("new page loaded");
pageLoaded = true;
reset();
try {
Thread.sleep(5000);
System.out.println(
"on page load:" + session.getWebInspector().getProtocol().sendCommand(DOM.getDocument())
.optJSONObject("root").optString("documentURL"));
} catch (Exception e) {
e.printStackTrace();
}
}
#location 9
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void setValueNative(String value) throws Exception {
/*WebElement el = getNativeElement();
WorkingMode origin = session.getMode();
try {
session.setMode(WorkingMode.Native);
el.click();
RemoteUIAKeyboard keyboard = (RemoteUIAKeyboard) session.getNativeDriver().getKeyboard();
if ("\n".equals(value)) {
keyboard.findElement(new NameCriteria("Return")).tap();
} else {
keyboard.sendKeys(value);
}
Criteria iphone = new NameCriteria("Done");
Criteria ipad = new NameCriteria("Hide keyboard");
UIAButton but = session.getNativeDriver().findElement(new OrCriteria(ipad, iphone));
but.tap();
// session.getNativeDriver().pinchClose(300, 400, 50, 100, 1);
} finally {
session.setMode(origin);
}*/
WorkingMode origin = session.getMode();
session.setMode(WorkingMode.Native);
((JavascriptExecutor) nativeDriver).executeScript(getNativeElementClickOnItAndTypeUsingKeyboardScript(value));
session.setMode(origin);
} | #vulnerable code
public void setValueNative(String value) throws Exception {
UIAElement el = getNativeElement();
WorkingMode origin = session.getMode();
try {
session.setMode(WorkingMode.Native);
UIARect rect = el.getRect();
int x = rect.getX() + rect.getWidth() - 1;
int y = rect.getY() + rect.getHeight() / 2;
// TODO freynaud : tap() should take a param like middle, topLeft,
// bottomRight to save 1 call.
session.getNativeDriver().tap(x, y);
RemoteUIAKeyboard keyboard = (RemoteUIAKeyboard) session.getNativeDriver().getKeyboard();
if ("\n".equals(value)) {
keyboard.findElement(new NameCriteria("Return")).tap();
} else {
keyboard.sendKeys(value);
}
Criteria iphone = new NameCriteria("Done");
Criteria ipad = new NameCriteria("Hide keyboard");
UIAButton but = session.getNativeDriver().findElement(new OrCriteria(ipad, iphone));
but.tap();
// session.getNativeDriver().pinchClose(300, 400, 50, 100, 1);
} finally {
session.setMode(origin);
}
}
#location 16
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private File createTmpScript(String content) throws IOException {
File res=null;
if (DEBUG){
res = new File("/Users/freynaud/Documents/debug.js");
}else {
res = File.createTempFile(FILE_NAME, ".js");
}
Writer writer = new FileWriter(res);
IOUtils.copy(IOUtils.toInputStream(content),writer, "UTF-8");
IOUtils.closeQuietly(writer);
return res;
} | #vulnerable code
private File createTmpScript(String content) throws IOException {
File res = File.createTempFile(FILE_NAME, ".js");
BufferedWriter out = new BufferedWriter(new FileWriter(res));
out.write(content);
out.close();
return res;
}
#location 6
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testTrivialMethod() throws Exception {
Object obj = makeCall("someMethod");
assertEquals(1, obj.getClass().getField("runCounter").get(obj));
checkStats("someMethod", 1, 0, 1);
} | #vulnerable code
@Test
public void testTrivialMethod() throws Exception {
lib.simple("com.jitlogic.zorka.spy.unittest.SomeClass", "someMethod",
"zorka:type=ZorkaStats,name=SomeClass", "stats");
Object obj = TestUtil.instrumentAndInstantiate(spy,
"com.jitlogic.zorka.spy.unittest.SomeClass");
assertNotNull(obj);
TestUtil.callMethod(obj, "someMethod");
checkStats("someMethod", 1, 0, 1);
}
#location 11
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public boolean onActivate(Item item, Player player) {
if (player == null) {
return false;
}
double rotation = (player.yaw - 90) % 360;
if (rotation < 0) {
rotation += 360.0;
}
int[][] faces = new int[][]{
{0, 2},
{1, 3}
};
int originDirection = this.meta & 0x01;
int direction;
if (originDirection == 0) {
if (rotation >= 0 && rotation < 180) {
direction = 2;
} else {
direction = 0;
}
} else {
if (rotation >= 90 && rotation < 270) {
direction = 3;
} else {
direction = 1;
}
}
this.meta = direction | ((~this.meta) & 0x04);
this.getLevel().setBlock(this, this, true);
this.getLevel().addSound(new DoorSound(this));
return true;
} | #vulnerable code
@Override
public boolean onActivate(Item item, Player player) {
int[] faces = new int[]{3, 0, 1, 2};
this.meta = (faces[(player != null) ? player.getDirection() : 0] & 0x03) | ((~this.meta) & 0x04);
this.getLevel().setBlock(this, this, true);
this.getLevel().addSound(new DoorSound(this));
return true;
}
#location 4
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void openSession(String identifier, String address, int port, long clientID) {
PlayerCreationEvent ev = new PlayerCreationEvent(this, Player.class, Player.class, null, address, port);
this.server.getPluginManager().callEvent(ev);
Class<? extends Player> clazz = ev.getPlayerClass();
try {
Constructor constructor = clazz.getConstructor(SourceInterface.class, Long.class, String.class, int.class);
Player player = (Player) constructor.newInstance(this, ev.getClientId(), ev.getAddress(), ev.getPort());
this.players.put(identifier, player);
this.identifiersACK.put(identifier, 0);
this.identifiers.put(player, identifier);
this.server.addPlayer(identifier, player);
} catch (NoSuchMethodException | InvocationTargetException | InstantiationException | IllegalAccessException e) {
e.printStackTrace();
}
} | #vulnerable code
@Override
public void openSession(String identifier, String address, int port, long clientID) {
PlayerCreationEvent ev = new PlayerCreationEvent(this, Player.class, Player.class, null, address, port);
this.server.getPluginManager().callEvent(ev);
Class<? extends Player> clazz = ev.getPlayerClass();
try {
Constructor constructor = clazz.getConstructor(SourceInterface.class, Long.class, String.class, Integer.class);
Player player = (Player) constructor.newInstance(this, ev.getClientId(), ev.getAddress(), ev.getPort());
this.players.put(identifier, player);
this.identifiersACK.put(identifier, 0);
this.identifiers.put(player, identifier);
this.server.addPlayer(identifier, player);
} catch (NoSuchMethodException | InvocationTargetException | InstantiationException | IllegalAccessException e) {
e.printStackTrace();
}
}
#location 3
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public boolean getDataFlag(int propertyId, int id) {
return ((this.getDataPropertyByte(propertyId).data & 0xff) & (1 << id)) > 0;
} | #vulnerable code
public boolean getDataFlag(int propertyId, int id) {
return ((this.getDataPropertyByte(propertyId) == null ? 0 : this.getDataPropertyByte(propertyId).data & 0xff) & (1 << id)) > 0;
}
#location 2
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testSpecialStyles() throws Exception {
File f = new File("src/test/resources/special_types.xlsx");
Map<Integer, List<Cell>> contents = new HashMap<>();
try(Workbook wb = StreamingReader.builder().open(f)) {
for(Row row : wb.getSheetAt(0)) {
contents.put(row.getRowNum(), new ArrayList<Cell>());
for(Cell c : row) {
if(c.getColumnIndex() > 0) {
contents.get(row.getRowNum()).add(c);
}
}
}
}
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
assertThat(contents.size(), equalTo(2));
assertThat(contents.get(0).size(), equalTo(4));
assertThat(contents.get(0).get(0).getStringCellValue(), equalTo("Thu\", \"Dec 25\", \"14"));
assertThat(contents.get(0).get(0).getDateCellValue(), equalTo(df.parse("25/12/2014")));
assertThat(contents.get(0).get(1).getStringCellValue(), equalTo("02/04/15"));
assertThat(contents.get(0).get(1).getDateCellValue(), equalTo(df.parse("04/02/2015")));
assertThat(contents.get(0).get(2).getStringCellValue(), equalTo("14\". \"Mar\". \"2015"));
assertThat(contents.get(0).get(2).getDateCellValue(), equalTo(df.parse("14/03/2015")));
assertThat(contents.get(0).get(3).getStringCellValue(), equalTo("2015-05-05"));
assertThat(contents.get(0).get(3).getDateCellValue(), equalTo(df.parse("05/05/2015")));
assertThat(contents.get(1).size(), equalTo(4));
assertThat(contents.get(1).get(0).getStringCellValue(), equalTo("3.12"));
assertThat(contents.get(1).get(0).getNumericCellValue(), equalTo(3.12312312312));
assertThat(contents.get(1).get(1).getStringCellValue(), equalTo("1,023,042"));
assertThat(contents.get(1).get(1).getNumericCellValue(), equalTo(1023042.0));
assertThat(contents.get(1).get(2).getStringCellValue(), equalTo("-312,231.12"));
assertThat(contents.get(1).get(2).getNumericCellValue(), equalTo(-312231.12123145));
assertThat(contents.get(1).get(3).getStringCellValue(), equalTo("(132)"));
assertThat(contents.get(1).get(3).getNumericCellValue(), equalTo(-132.0));
} | #vulnerable code
@Test
public void testSpecialStyles() throws Exception {
File f = new File("src/test/resources/special_types.xlsx");
Map<Integer, List<Cell>> contents = new HashMap<>();
try(StreamingReader reader = StreamingReader.builder().read(f)) {
for(Row row : reader) {
contents.put(row.getRowNum(), new ArrayList<Cell>());
for(Cell c : row) {
if(c.getColumnIndex() > 0) {
contents.get(row.getRowNum()).add(c);
}
}
}
}
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
assertThat(contents.size(), equalTo(2));
assertThat(contents.get(0).size(), equalTo(4));
assertThat(contents.get(0).get(0).getStringCellValue(), equalTo("Thu\", \"Dec 25\", \"14"));
assertThat(contents.get(0).get(0).getDateCellValue(), equalTo(df.parse("25/12/2014")));
assertThat(contents.get(0).get(1).getStringCellValue(), equalTo("02/04/15"));
assertThat(contents.get(0).get(1).getDateCellValue(), equalTo(df.parse("04/02/2015")));
assertThat(contents.get(0).get(2).getStringCellValue(), equalTo("14\". \"Mar\". \"2015"));
assertThat(contents.get(0).get(2).getDateCellValue(), equalTo(df.parse("14/03/2015")));
assertThat(contents.get(0).get(3).getStringCellValue(), equalTo("2015-05-05"));
assertThat(contents.get(0).get(3).getDateCellValue(), equalTo(df.parse("05/05/2015")));
assertThat(contents.get(1).size(), equalTo(4));
assertThat(contents.get(1).get(0).getStringCellValue(), equalTo("3.12"));
assertThat(contents.get(1).get(0).getNumericCellValue(), equalTo(3.12312312312));
assertThat(contents.get(1).get(1).getStringCellValue(), equalTo("1,023,042"));
assertThat(contents.get(1).get(1).getNumericCellValue(), equalTo(1023042.0));
assertThat(contents.get(1).get(2).getStringCellValue(), equalTo("-312,231.12"));
assertThat(contents.get(1).get(2).getNumericCellValue(), equalTo(-312231.12123145));
assertThat(contents.get(1).get(3).getStringCellValue(), equalTo("(132)"));
assertThat(contents.get(1).get(3).getNumericCellValue(), equalTo(-132.0));
}
#location 20
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testSpecialStyles() throws Exception {
File f = new File("src/test/resources/special_types.xlsx");
Map<Integer, List<Cell>> contents = new HashMap<>();
try(Workbook wb = StreamingReader.builder().open(f)) {
for(Row row : wb.getSheetAt(0)) {
contents.put(row.getRowNum(), new ArrayList<Cell>());
for(Cell c : row) {
if(c.getColumnIndex() > 0) {
contents.get(row.getRowNum()).add(c);
}
}
}
}
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
assertThat(contents.size(), equalTo(2));
assertThat(contents.get(0).size(), equalTo(4));
assertThat(contents.get(0).get(0).getStringCellValue(), equalTo("Thu\", \"Dec 25\", \"14"));
assertThat(contents.get(0).get(0).getDateCellValue(), equalTo(df.parse("25/12/2014")));
assertThat(contents.get(0).get(1).getStringCellValue(), equalTo("02/04/15"));
assertThat(contents.get(0).get(1).getDateCellValue(), equalTo(df.parse("04/02/2015")));
assertThat(contents.get(0).get(2).getStringCellValue(), equalTo("14\". \"Mar\". \"2015"));
assertThat(contents.get(0).get(2).getDateCellValue(), equalTo(df.parse("14/03/2015")));
assertThat(contents.get(0).get(3).getStringCellValue(), equalTo("2015-05-05"));
assertThat(contents.get(0).get(3).getDateCellValue(), equalTo(df.parse("05/05/2015")));
assertThat(contents.get(1).size(), equalTo(4));
assertThat(contents.get(1).get(0).getStringCellValue(), equalTo("3.12"));
assertThat(contents.get(1).get(0).getNumericCellValue(), equalTo(3.12312312312));
assertThat(contents.get(1).get(1).getStringCellValue(), equalTo("1,023,042"));
assertThat(contents.get(1).get(1).getNumericCellValue(), equalTo(1023042.0));
assertThat(contents.get(1).get(2).getStringCellValue(), equalTo("-312,231.12"));
assertThat(contents.get(1).get(2).getNumericCellValue(), equalTo(-312231.12123145));
assertThat(contents.get(1).get(3).getStringCellValue(), equalTo("(132)"));
assertThat(contents.get(1).get(3).getNumericCellValue(), equalTo(-132.0));
} | #vulnerable code
@Test
public void testSpecialStyles() throws Exception {
File f = new File("src/test/resources/special_types.xlsx");
Map<Integer, List<Cell>> contents = new HashMap<>();
try(StreamingReader reader = StreamingReader.builder().read(f)) {
for(Row row : reader) {
contents.put(row.getRowNum(), new ArrayList<Cell>());
for(Cell c : row) {
if(c.getColumnIndex() > 0) {
contents.get(row.getRowNum()).add(c);
}
}
}
}
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
assertThat(contents.size(), equalTo(2));
assertThat(contents.get(0).size(), equalTo(4));
assertThat(contents.get(0).get(0).getStringCellValue(), equalTo("Thu\", \"Dec 25\", \"14"));
assertThat(contents.get(0).get(0).getDateCellValue(), equalTo(df.parse("25/12/2014")));
assertThat(contents.get(0).get(1).getStringCellValue(), equalTo("02/04/15"));
assertThat(contents.get(0).get(1).getDateCellValue(), equalTo(df.parse("04/02/2015")));
assertThat(contents.get(0).get(2).getStringCellValue(), equalTo("14\". \"Mar\". \"2015"));
assertThat(contents.get(0).get(2).getDateCellValue(), equalTo(df.parse("14/03/2015")));
assertThat(contents.get(0).get(3).getStringCellValue(), equalTo("2015-05-05"));
assertThat(contents.get(0).get(3).getDateCellValue(), equalTo(df.parse("05/05/2015")));
assertThat(contents.get(1).size(), equalTo(4));
assertThat(contents.get(1).get(0).getStringCellValue(), equalTo("3.12"));
assertThat(contents.get(1).get(0).getNumericCellValue(), equalTo(3.12312312312));
assertThat(contents.get(1).get(1).getStringCellValue(), equalTo("1,023,042"));
assertThat(contents.get(1).get(1).getNumericCellValue(), equalTo(1023042.0));
assertThat(contents.get(1).get(2).getStringCellValue(), equalTo("-312,231.12"));
assertThat(contents.get(1).get(2).getNumericCellValue(), equalTo(-312231.12123145));
assertThat(contents.get(1).get(3).getStringCellValue(), equalTo("(132)"));
assertThat(contents.get(1).get(3).getNumericCellValue(), equalTo(-132.0));
}
#location 31
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testSpecialStyles() throws Exception {
File f = new File("src/test/resources/special_types.xlsx");
Map<Integer, List<Cell>> contents = new HashMap<>();
try(Workbook wb = StreamingReader.builder().open(f)) {
for(Row row : wb.getSheetAt(0)) {
contents.put(row.getRowNum(), new ArrayList<Cell>());
for(Cell c : row) {
if(c.getColumnIndex() > 0) {
contents.get(row.getRowNum()).add(c);
}
}
}
}
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
assertThat(contents.size(), equalTo(2));
assertThat(contents.get(0).size(), equalTo(4));
assertThat(contents.get(0).get(0).getStringCellValue(), equalTo("Thu\", \"Dec 25\", \"14"));
assertThat(contents.get(0).get(0).getDateCellValue(), equalTo(df.parse("25/12/2014")));
assertThat(contents.get(0).get(1).getStringCellValue(), equalTo("02/04/15"));
assertThat(contents.get(0).get(1).getDateCellValue(), equalTo(df.parse("04/02/2015")));
assertThat(contents.get(0).get(2).getStringCellValue(), equalTo("14\". \"Mar\". \"2015"));
assertThat(contents.get(0).get(2).getDateCellValue(), equalTo(df.parse("14/03/2015")));
assertThat(contents.get(0).get(3).getStringCellValue(), equalTo("2015-05-05"));
assertThat(contents.get(0).get(3).getDateCellValue(), equalTo(df.parse("05/05/2015")));
assertThat(contents.get(1).size(), equalTo(4));
assertThat(contents.get(1).get(0).getStringCellValue(), equalTo("3.12"));
assertThat(contents.get(1).get(0).getNumericCellValue(), equalTo(3.12312312312));
assertThat(contents.get(1).get(1).getStringCellValue(), equalTo("1,023,042"));
assertThat(contents.get(1).get(1).getNumericCellValue(), equalTo(1023042.0));
assertThat(contents.get(1).get(2).getStringCellValue(), equalTo("-312,231.12"));
assertThat(contents.get(1).get(2).getNumericCellValue(), equalTo(-312231.12123145));
assertThat(contents.get(1).get(3).getStringCellValue(), equalTo("(132)"));
assertThat(contents.get(1).get(3).getNumericCellValue(), equalTo(-132.0));
} | #vulnerable code
@Test
public void testSpecialStyles() throws Exception {
File f = new File("src/test/resources/special_types.xlsx");
Map<Integer, List<Cell>> contents = new HashMap<>();
try(StreamingReader reader = StreamingReader.builder().read(f)) {
for(Row row : reader) {
contents.put(row.getRowNum(), new ArrayList<Cell>());
for(Cell c : row) {
if(c.getColumnIndex() > 0) {
contents.get(row.getRowNum()).add(c);
}
}
}
}
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
assertThat(contents.size(), equalTo(2));
assertThat(contents.get(0).size(), equalTo(4));
assertThat(contents.get(0).get(0).getStringCellValue(), equalTo("Thu\", \"Dec 25\", \"14"));
assertThat(contents.get(0).get(0).getDateCellValue(), equalTo(df.parse("25/12/2014")));
assertThat(contents.get(0).get(1).getStringCellValue(), equalTo("02/04/15"));
assertThat(contents.get(0).get(1).getDateCellValue(), equalTo(df.parse("04/02/2015")));
assertThat(contents.get(0).get(2).getStringCellValue(), equalTo("14\". \"Mar\". \"2015"));
assertThat(contents.get(0).get(2).getDateCellValue(), equalTo(df.parse("14/03/2015")));
assertThat(contents.get(0).get(3).getStringCellValue(), equalTo("2015-05-05"));
assertThat(contents.get(0).get(3).getDateCellValue(), equalTo(df.parse("05/05/2015")));
assertThat(contents.get(1).size(), equalTo(4));
assertThat(contents.get(1).get(0).getStringCellValue(), equalTo("3.12"));
assertThat(contents.get(1).get(0).getNumericCellValue(), equalTo(3.12312312312));
assertThat(contents.get(1).get(1).getStringCellValue(), equalTo("1,023,042"));
assertThat(contents.get(1).get(1).getNumericCellValue(), equalTo(1023042.0));
assertThat(contents.get(1).get(2).getStringCellValue(), equalTo("-312,231.12"));
assertThat(contents.get(1).get(2).getNumericCellValue(), equalTo(-312231.12123145));
assertThat(contents.get(1).get(3).getStringCellValue(), equalTo("(132)"));
assertThat(contents.get(1).get(3).getNumericCellValue(), equalTo(-132.0));
}
#location 23
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testSpecialStyles() throws Exception {
File f = new File("src/test/resources/special_types.xlsx");
Map<Integer, List<Cell>> contents = new HashMap<>();
try(Workbook wb = StreamingReader.builder().open(f)) {
for(Row row : wb.getSheetAt(0)) {
contents.put(row.getRowNum(), new ArrayList<Cell>());
for(Cell c : row) {
if(c.getColumnIndex() > 0) {
contents.get(row.getRowNum()).add(c);
}
}
}
}
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
assertThat(contents.size(), equalTo(2));
assertThat(contents.get(0).size(), equalTo(4));
assertThat(contents.get(0).get(0).getStringCellValue(), equalTo("Thu\", \"Dec 25\", \"14"));
assertThat(contents.get(0).get(0).getDateCellValue(), equalTo(df.parse("25/12/2014")));
assertThat(contents.get(0).get(1).getStringCellValue(), equalTo("02/04/15"));
assertThat(contents.get(0).get(1).getDateCellValue(), equalTo(df.parse("04/02/2015")));
assertThat(contents.get(0).get(2).getStringCellValue(), equalTo("14\". \"Mar\". \"2015"));
assertThat(contents.get(0).get(2).getDateCellValue(), equalTo(df.parse("14/03/2015")));
assertThat(contents.get(0).get(3).getStringCellValue(), equalTo("2015-05-05"));
assertThat(contents.get(0).get(3).getDateCellValue(), equalTo(df.parse("05/05/2015")));
assertThat(contents.get(1).size(), equalTo(4));
assertThat(contents.get(1).get(0).getStringCellValue(), equalTo("3.12"));
assertThat(contents.get(1).get(0).getNumericCellValue(), equalTo(3.12312312312));
assertThat(contents.get(1).get(1).getStringCellValue(), equalTo("1,023,042"));
assertThat(contents.get(1).get(1).getNumericCellValue(), equalTo(1023042.0));
assertThat(contents.get(1).get(2).getStringCellValue(), equalTo("-312,231.12"));
assertThat(contents.get(1).get(2).getNumericCellValue(), equalTo(-312231.12123145));
assertThat(contents.get(1).get(3).getStringCellValue(), equalTo("(132)"));
assertThat(contents.get(1).get(3).getNumericCellValue(), equalTo(-132.0));
} | #vulnerable code
@Test
public void testSpecialStyles() throws Exception {
File f = new File("src/test/resources/special_types.xlsx");
Map<Integer, List<Cell>> contents = new HashMap<>();
try(StreamingReader reader = StreamingReader.builder().read(f)) {
for(Row row : reader) {
contents.put(row.getRowNum(), new ArrayList<Cell>());
for(Cell c : row) {
if(c.getColumnIndex() > 0) {
contents.get(row.getRowNum()).add(c);
}
}
}
}
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
assertThat(contents.size(), equalTo(2));
assertThat(contents.get(0).size(), equalTo(4));
assertThat(contents.get(0).get(0).getStringCellValue(), equalTo("Thu\", \"Dec 25\", \"14"));
assertThat(contents.get(0).get(0).getDateCellValue(), equalTo(df.parse("25/12/2014")));
assertThat(contents.get(0).get(1).getStringCellValue(), equalTo("02/04/15"));
assertThat(contents.get(0).get(1).getDateCellValue(), equalTo(df.parse("04/02/2015")));
assertThat(contents.get(0).get(2).getStringCellValue(), equalTo("14\". \"Mar\". \"2015"));
assertThat(contents.get(0).get(2).getDateCellValue(), equalTo(df.parse("14/03/2015")));
assertThat(contents.get(0).get(3).getStringCellValue(), equalTo("2015-05-05"));
assertThat(contents.get(0).get(3).getDateCellValue(), equalTo(df.parse("05/05/2015")));
assertThat(contents.get(1).size(), equalTo(4));
assertThat(contents.get(1).get(0).getStringCellValue(), equalTo("3.12"));
assertThat(contents.get(1).get(0).getNumericCellValue(), equalTo(3.12312312312));
assertThat(contents.get(1).get(1).getStringCellValue(), equalTo("1,023,042"));
assertThat(contents.get(1).get(1).getNumericCellValue(), equalTo(1023042.0));
assertThat(contents.get(1).get(2).getStringCellValue(), equalTo("-312,231.12"));
assertThat(contents.get(1).get(2).getNumericCellValue(), equalTo(-312231.12123145));
assertThat(contents.get(1).get(3).getStringCellValue(), equalTo("(132)"));
assertThat(contents.get(1).get(3).getNumericCellValue(), equalTo(-132.0));
}
#location 30
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testSpecialStyles() throws Exception {
File f = new File("src/test/resources/special_types.xlsx");
Map<Integer, List<Cell>> contents = new HashMap<>();
try(Workbook wb = StreamingReader.builder().open(f)) {
for(Row row : wb.getSheetAt(0)) {
contents.put(row.getRowNum(), new ArrayList<Cell>());
for(Cell c : row) {
if(c.getColumnIndex() > 0) {
contents.get(row.getRowNum()).add(c);
}
}
}
}
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
assertThat(contents.size(), equalTo(2));
assertThat(contents.get(0).size(), equalTo(4));
assertThat(contents.get(0).get(0).getStringCellValue(), equalTo("Thu\", \"Dec 25\", \"14"));
assertThat(contents.get(0).get(0).getDateCellValue(), equalTo(df.parse("25/12/2014")));
assertThat(contents.get(0).get(1).getStringCellValue(), equalTo("02/04/15"));
assertThat(contents.get(0).get(1).getDateCellValue(), equalTo(df.parse("04/02/2015")));
assertThat(contents.get(0).get(2).getStringCellValue(), equalTo("14\". \"Mar\". \"2015"));
assertThat(contents.get(0).get(2).getDateCellValue(), equalTo(df.parse("14/03/2015")));
assertThat(contents.get(0).get(3).getStringCellValue(), equalTo("2015-05-05"));
assertThat(contents.get(0).get(3).getDateCellValue(), equalTo(df.parse("05/05/2015")));
assertThat(contents.get(1).size(), equalTo(4));
assertThat(contents.get(1).get(0).getStringCellValue(), equalTo("3.12"));
assertThat(contents.get(1).get(0).getNumericCellValue(), equalTo(3.12312312312));
assertThat(contents.get(1).get(1).getStringCellValue(), equalTo("1,023,042"));
assertThat(contents.get(1).get(1).getNumericCellValue(), equalTo(1023042.0));
assertThat(contents.get(1).get(2).getStringCellValue(), equalTo("-312,231.12"));
assertThat(contents.get(1).get(2).getNumericCellValue(), equalTo(-312231.12123145));
assertThat(contents.get(1).get(3).getStringCellValue(), equalTo("(132)"));
assertThat(contents.get(1).get(3).getNumericCellValue(), equalTo(-132.0));
} | #vulnerable code
@Test
public void testSpecialStyles() throws Exception {
File f = new File("src/test/resources/special_types.xlsx");
Map<Integer, List<Cell>> contents = new HashMap<>();
try(StreamingReader reader = StreamingReader.builder().read(f)) {
for(Row row : reader) {
contents.put(row.getRowNum(), new ArrayList<Cell>());
for(Cell c : row) {
if(c.getColumnIndex() > 0) {
contents.get(row.getRowNum()).add(c);
}
}
}
}
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
assertThat(contents.size(), equalTo(2));
assertThat(contents.get(0).size(), equalTo(4));
assertThat(contents.get(0).get(0).getStringCellValue(), equalTo("Thu\", \"Dec 25\", \"14"));
assertThat(contents.get(0).get(0).getDateCellValue(), equalTo(df.parse("25/12/2014")));
assertThat(contents.get(0).get(1).getStringCellValue(), equalTo("02/04/15"));
assertThat(contents.get(0).get(1).getDateCellValue(), equalTo(df.parse("04/02/2015")));
assertThat(contents.get(0).get(2).getStringCellValue(), equalTo("14\". \"Mar\". \"2015"));
assertThat(contents.get(0).get(2).getDateCellValue(), equalTo(df.parse("14/03/2015")));
assertThat(contents.get(0).get(3).getStringCellValue(), equalTo("2015-05-05"));
assertThat(contents.get(0).get(3).getDateCellValue(), equalTo(df.parse("05/05/2015")));
assertThat(contents.get(1).size(), equalTo(4));
assertThat(contents.get(1).get(0).getStringCellValue(), equalTo("3.12"));
assertThat(contents.get(1).get(0).getNumericCellValue(), equalTo(3.12312312312));
assertThat(contents.get(1).get(1).getStringCellValue(), equalTo("1,023,042"));
assertThat(contents.get(1).get(1).getNumericCellValue(), equalTo(1023042.0));
assertThat(contents.get(1).get(2).getStringCellValue(), equalTo("-312,231.12"));
assertThat(contents.get(1).get(2).getNumericCellValue(), equalTo(-312231.12123145));
assertThat(contents.get(1).get(3).getStringCellValue(), equalTo("(132)"));
assertThat(contents.get(1).get(3).getNumericCellValue(), equalTo(-132.0));
}
#location 26
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testSpecialStyles() throws Exception {
File f = new File("src/test/resources/special_types.xlsx");
Map<Integer, List<Cell>> contents = new HashMap<>();
try(Workbook wb = StreamingReader.builder().open(f)) {
for(Row row : wb.getSheetAt(0)) {
contents.put(row.getRowNum(), new ArrayList<Cell>());
for(Cell c : row) {
if(c.getColumnIndex() > 0) {
contents.get(row.getRowNum()).add(c);
}
}
}
}
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
assertThat(contents.size(), equalTo(2));
assertThat(contents.get(0).size(), equalTo(4));
assertThat(contents.get(0).get(0).getStringCellValue(), equalTo("Thu\", \"Dec 25\", \"14"));
assertThat(contents.get(0).get(0).getDateCellValue(), equalTo(df.parse("25/12/2014")));
assertThat(contents.get(0).get(1).getStringCellValue(), equalTo("02/04/15"));
assertThat(contents.get(0).get(1).getDateCellValue(), equalTo(df.parse("04/02/2015")));
assertThat(contents.get(0).get(2).getStringCellValue(), equalTo("14\". \"Mar\". \"2015"));
assertThat(contents.get(0).get(2).getDateCellValue(), equalTo(df.parse("14/03/2015")));
assertThat(contents.get(0).get(3).getStringCellValue(), equalTo("2015-05-05"));
assertThat(contents.get(0).get(3).getDateCellValue(), equalTo(df.parse("05/05/2015")));
assertThat(contents.get(1).size(), equalTo(4));
assertThat(contents.get(1).get(0).getStringCellValue(), equalTo("3.12"));
assertThat(contents.get(1).get(0).getNumericCellValue(), equalTo(3.12312312312));
assertThat(contents.get(1).get(1).getStringCellValue(), equalTo("1,023,042"));
assertThat(contents.get(1).get(1).getNumericCellValue(), equalTo(1023042.0));
assertThat(contents.get(1).get(2).getStringCellValue(), equalTo("-312,231.12"));
assertThat(contents.get(1).get(2).getNumericCellValue(), equalTo(-312231.12123145));
assertThat(contents.get(1).get(3).getStringCellValue(), equalTo("(132)"));
assertThat(contents.get(1).get(3).getNumericCellValue(), equalTo(-132.0));
} | #vulnerable code
@Test
public void testSpecialStyles() throws Exception {
File f = new File("src/test/resources/special_types.xlsx");
Map<Integer, List<Cell>> contents = new HashMap<>();
try(StreamingReader reader = StreamingReader.builder().read(f)) {
for(Row row : reader) {
contents.put(row.getRowNum(), new ArrayList<Cell>());
for(Cell c : row) {
if(c.getColumnIndex() > 0) {
contents.get(row.getRowNum()).add(c);
}
}
}
}
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
assertThat(contents.size(), equalTo(2));
assertThat(contents.get(0).size(), equalTo(4));
assertThat(contents.get(0).get(0).getStringCellValue(), equalTo("Thu\", \"Dec 25\", \"14"));
assertThat(contents.get(0).get(0).getDateCellValue(), equalTo(df.parse("25/12/2014")));
assertThat(contents.get(0).get(1).getStringCellValue(), equalTo("02/04/15"));
assertThat(contents.get(0).get(1).getDateCellValue(), equalTo(df.parse("04/02/2015")));
assertThat(contents.get(0).get(2).getStringCellValue(), equalTo("14\". \"Mar\". \"2015"));
assertThat(contents.get(0).get(2).getDateCellValue(), equalTo(df.parse("14/03/2015")));
assertThat(contents.get(0).get(3).getStringCellValue(), equalTo("2015-05-05"));
assertThat(contents.get(0).get(3).getDateCellValue(), equalTo(df.parse("05/05/2015")));
assertThat(contents.get(1).size(), equalTo(4));
assertThat(contents.get(1).get(0).getStringCellValue(), equalTo("3.12"));
assertThat(contents.get(1).get(0).getNumericCellValue(), equalTo(3.12312312312));
assertThat(contents.get(1).get(1).getStringCellValue(), equalTo("1,023,042"));
assertThat(contents.get(1).get(1).getNumericCellValue(), equalTo(1023042.0));
assertThat(contents.get(1).get(2).getStringCellValue(), equalTo("-312,231.12"));
assertThat(contents.get(1).get(2).getNumericCellValue(), equalTo(-312231.12123145));
assertThat(contents.get(1).get(3).getStringCellValue(), equalTo("(132)"));
assertThat(contents.get(1).get(3).getNumericCellValue(), equalTo(-132.0));
}
#location 28
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testSpecialStyles() throws Exception {
File f = new File("src/test/resources/special_types.xlsx");
Map<Integer, List<Cell>> contents = new HashMap<>();
try(Workbook wb = StreamingReader.builder().open(f)) {
for(Row row : wb.getSheetAt(0)) {
contents.put(row.getRowNum(), new ArrayList<Cell>());
for(Cell c : row) {
if(c.getColumnIndex() > 0) {
contents.get(row.getRowNum()).add(c);
}
}
}
}
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
assertThat(contents.size(), equalTo(2));
assertThat(contents.get(0).size(), equalTo(4));
assertThat(contents.get(0).get(0).getStringCellValue(), equalTo("Thu\", \"Dec 25\", \"14"));
assertThat(contents.get(0).get(0).getDateCellValue(), equalTo(df.parse("25/12/2014")));
assertThat(contents.get(0).get(1).getStringCellValue(), equalTo("02/04/15"));
assertThat(contents.get(0).get(1).getDateCellValue(), equalTo(df.parse("04/02/2015")));
assertThat(contents.get(0).get(2).getStringCellValue(), equalTo("14\". \"Mar\". \"2015"));
assertThat(contents.get(0).get(2).getDateCellValue(), equalTo(df.parse("14/03/2015")));
assertThat(contents.get(0).get(3).getStringCellValue(), equalTo("2015-05-05"));
assertThat(contents.get(0).get(3).getDateCellValue(), equalTo(df.parse("05/05/2015")));
assertThat(contents.get(1).size(), equalTo(4));
assertThat(contents.get(1).get(0).getStringCellValue(), equalTo("3.12"));
assertThat(contents.get(1).get(0).getNumericCellValue(), equalTo(3.12312312312));
assertThat(contents.get(1).get(1).getStringCellValue(), equalTo("1,023,042"));
assertThat(contents.get(1).get(1).getNumericCellValue(), equalTo(1023042.0));
assertThat(contents.get(1).get(2).getStringCellValue(), equalTo("-312,231.12"));
assertThat(contents.get(1).get(2).getNumericCellValue(), equalTo(-312231.12123145));
assertThat(contents.get(1).get(3).getStringCellValue(), equalTo("(132)"));
assertThat(contents.get(1).get(3).getNumericCellValue(), equalTo(-132.0));
} | #vulnerable code
@Test
public void testSpecialStyles() throws Exception {
File f = new File("src/test/resources/special_types.xlsx");
Map<Integer, List<Cell>> contents = new HashMap<>();
try(StreamingReader reader = StreamingReader.builder().read(f)) {
for(Row row : reader) {
contents.put(row.getRowNum(), new ArrayList<Cell>());
for(Cell c : row) {
if(c.getColumnIndex() > 0) {
contents.get(row.getRowNum()).add(c);
}
}
}
}
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
assertThat(contents.size(), equalTo(2));
assertThat(contents.get(0).size(), equalTo(4));
assertThat(contents.get(0).get(0).getStringCellValue(), equalTo("Thu\", \"Dec 25\", \"14"));
assertThat(contents.get(0).get(0).getDateCellValue(), equalTo(df.parse("25/12/2014")));
assertThat(contents.get(0).get(1).getStringCellValue(), equalTo("02/04/15"));
assertThat(contents.get(0).get(1).getDateCellValue(), equalTo(df.parse("04/02/2015")));
assertThat(contents.get(0).get(2).getStringCellValue(), equalTo("14\". \"Mar\". \"2015"));
assertThat(contents.get(0).get(2).getDateCellValue(), equalTo(df.parse("14/03/2015")));
assertThat(contents.get(0).get(3).getStringCellValue(), equalTo("2015-05-05"));
assertThat(contents.get(0).get(3).getDateCellValue(), equalTo(df.parse("05/05/2015")));
assertThat(contents.get(1).size(), equalTo(4));
assertThat(contents.get(1).get(0).getStringCellValue(), equalTo("3.12"));
assertThat(contents.get(1).get(0).getNumericCellValue(), equalTo(3.12312312312));
assertThat(contents.get(1).get(1).getStringCellValue(), equalTo("1,023,042"));
assertThat(contents.get(1).get(1).getNumericCellValue(), equalTo(1023042.0));
assertThat(contents.get(1).get(2).getStringCellValue(), equalTo("-312,231.12"));
assertThat(contents.get(1).get(2).getNumericCellValue(), equalTo(-312231.12123145));
assertThat(contents.get(1).get(3).getStringCellValue(), equalTo("(132)"));
assertThat(contents.get(1).get(3).getNumericCellValue(), equalTo(-132.0));
}
#location 25
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testSpecialStyles() throws Exception {
File f = new File("src/test/resources/special_types.xlsx");
Map<Integer, List<Cell>> contents = new HashMap<>();
try(Workbook wb = StreamingReader.builder().open(f)) {
for(Row row : wb.getSheetAt(0)) {
contents.put(row.getRowNum(), new ArrayList<Cell>());
for(Cell c : row) {
if(c.getColumnIndex() > 0) {
contents.get(row.getRowNum()).add(c);
}
}
}
}
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
assertThat(contents.size(), equalTo(2));
assertThat(contents.get(0).size(), equalTo(4));
assertThat(contents.get(0).get(0).getStringCellValue(), equalTo("Thu\", \"Dec 25\", \"14"));
assertThat(contents.get(0).get(0).getDateCellValue(), equalTo(df.parse("25/12/2014")));
assertThat(contents.get(0).get(1).getStringCellValue(), equalTo("02/04/15"));
assertThat(contents.get(0).get(1).getDateCellValue(), equalTo(df.parse("04/02/2015")));
assertThat(contents.get(0).get(2).getStringCellValue(), equalTo("14\". \"Mar\". \"2015"));
assertThat(contents.get(0).get(2).getDateCellValue(), equalTo(df.parse("14/03/2015")));
assertThat(contents.get(0).get(3).getStringCellValue(), equalTo("2015-05-05"));
assertThat(contents.get(0).get(3).getDateCellValue(), equalTo(df.parse("05/05/2015")));
assertThat(contents.get(1).size(), equalTo(4));
assertThat(contents.get(1).get(0).getStringCellValue(), equalTo("3.12"));
assertThat(contents.get(1).get(0).getNumericCellValue(), equalTo(3.12312312312));
assertThat(contents.get(1).get(1).getStringCellValue(), equalTo("1,023,042"));
assertThat(contents.get(1).get(1).getNumericCellValue(), equalTo(1023042.0));
assertThat(contents.get(1).get(2).getStringCellValue(), equalTo("-312,231.12"));
assertThat(contents.get(1).get(2).getNumericCellValue(), equalTo(-312231.12123145));
assertThat(contents.get(1).get(3).getStringCellValue(), equalTo("(132)"));
assertThat(contents.get(1).get(3).getNumericCellValue(), equalTo(-132.0));
} | #vulnerable code
@Test
public void testSpecialStyles() throws Exception {
File f = new File("src/test/resources/special_types.xlsx");
Map<Integer, List<Cell>> contents = new HashMap<>();
try(StreamingReader reader = StreamingReader.builder().read(f)) {
for(Row row : reader) {
contents.put(row.getRowNum(), new ArrayList<Cell>());
for(Cell c : row) {
if(c.getColumnIndex() > 0) {
contents.get(row.getRowNum()).add(c);
}
}
}
}
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
assertThat(contents.size(), equalTo(2));
assertThat(contents.get(0).size(), equalTo(4));
assertThat(contents.get(0).get(0).getStringCellValue(), equalTo("Thu\", \"Dec 25\", \"14"));
assertThat(contents.get(0).get(0).getDateCellValue(), equalTo(df.parse("25/12/2014")));
assertThat(contents.get(0).get(1).getStringCellValue(), equalTo("02/04/15"));
assertThat(contents.get(0).get(1).getDateCellValue(), equalTo(df.parse("04/02/2015")));
assertThat(contents.get(0).get(2).getStringCellValue(), equalTo("14\". \"Mar\". \"2015"));
assertThat(contents.get(0).get(2).getDateCellValue(), equalTo(df.parse("14/03/2015")));
assertThat(contents.get(0).get(3).getStringCellValue(), equalTo("2015-05-05"));
assertThat(contents.get(0).get(3).getDateCellValue(), equalTo(df.parse("05/05/2015")));
assertThat(contents.get(1).size(), equalTo(4));
assertThat(contents.get(1).get(0).getStringCellValue(), equalTo("3.12"));
assertThat(contents.get(1).get(0).getNumericCellValue(), equalTo(3.12312312312));
assertThat(contents.get(1).get(1).getStringCellValue(), equalTo("1,023,042"));
assertThat(contents.get(1).get(1).getNumericCellValue(), equalTo(1023042.0));
assertThat(contents.get(1).get(2).getStringCellValue(), equalTo("-312,231.12"));
assertThat(contents.get(1).get(2).getNumericCellValue(), equalTo(-312231.12123145));
assertThat(contents.get(1).get(3).getStringCellValue(), equalTo("(132)"));
assertThat(contents.get(1).get(3).getNumericCellValue(), equalTo(-132.0));
}
#location 27
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testSpecialStyles() throws Exception {
File f = new File("src/test/resources/special_types.xlsx");
Map<Integer, List<Cell>> contents = new HashMap<>();
try(Workbook wb = StreamingReader.builder().open(f)) {
for(Row row : wb.getSheetAt(0)) {
contents.put(row.getRowNum(), new ArrayList<Cell>());
for(Cell c : row) {
if(c.getColumnIndex() > 0) {
contents.get(row.getRowNum()).add(c);
}
}
}
}
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
assertThat(contents.size(), equalTo(2));
assertThat(contents.get(0).size(), equalTo(4));
assertThat(contents.get(0).get(0).getStringCellValue(), equalTo("Thu\", \"Dec 25\", \"14"));
assertThat(contents.get(0).get(0).getDateCellValue(), equalTo(df.parse("25/12/2014")));
assertThat(contents.get(0).get(1).getStringCellValue(), equalTo("02/04/15"));
assertThat(contents.get(0).get(1).getDateCellValue(), equalTo(df.parse("04/02/2015")));
assertThat(contents.get(0).get(2).getStringCellValue(), equalTo("14\". \"Mar\". \"2015"));
assertThat(contents.get(0).get(2).getDateCellValue(), equalTo(df.parse("14/03/2015")));
assertThat(contents.get(0).get(3).getStringCellValue(), equalTo("2015-05-05"));
assertThat(contents.get(0).get(3).getDateCellValue(), equalTo(df.parse("05/05/2015")));
assertThat(contents.get(1).size(), equalTo(4));
assertThat(contents.get(1).get(0).getStringCellValue(), equalTo("3.12"));
assertThat(contents.get(1).get(0).getNumericCellValue(), equalTo(3.12312312312));
assertThat(contents.get(1).get(1).getStringCellValue(), equalTo("1,023,042"));
assertThat(contents.get(1).get(1).getNumericCellValue(), equalTo(1023042.0));
assertThat(contents.get(1).get(2).getStringCellValue(), equalTo("-312,231.12"));
assertThat(contents.get(1).get(2).getNumericCellValue(), equalTo(-312231.12123145));
assertThat(contents.get(1).get(3).getStringCellValue(), equalTo("(132)"));
assertThat(contents.get(1).get(3).getNumericCellValue(), equalTo(-132.0));
} | #vulnerable code
@Test
public void testSpecialStyles() throws Exception {
File f = new File("src/test/resources/special_types.xlsx");
Map<Integer, List<Cell>> contents = new HashMap<>();
try(StreamingReader reader = StreamingReader.builder().read(f)) {
for(Row row : reader) {
contents.put(row.getRowNum(), new ArrayList<Cell>());
for(Cell c : row) {
if(c.getColumnIndex() > 0) {
contents.get(row.getRowNum()).add(c);
}
}
}
}
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
assertThat(contents.size(), equalTo(2));
assertThat(contents.get(0).size(), equalTo(4));
assertThat(contents.get(0).get(0).getStringCellValue(), equalTo("Thu\", \"Dec 25\", \"14"));
assertThat(contents.get(0).get(0).getDateCellValue(), equalTo(df.parse("25/12/2014")));
assertThat(contents.get(0).get(1).getStringCellValue(), equalTo("02/04/15"));
assertThat(contents.get(0).get(1).getDateCellValue(), equalTo(df.parse("04/02/2015")));
assertThat(contents.get(0).get(2).getStringCellValue(), equalTo("14\". \"Mar\". \"2015"));
assertThat(contents.get(0).get(2).getDateCellValue(), equalTo(df.parse("14/03/2015")));
assertThat(contents.get(0).get(3).getStringCellValue(), equalTo("2015-05-05"));
assertThat(contents.get(0).get(3).getDateCellValue(), equalTo(df.parse("05/05/2015")));
assertThat(contents.get(1).size(), equalTo(4));
assertThat(contents.get(1).get(0).getStringCellValue(), equalTo("3.12"));
assertThat(contents.get(1).get(0).getNumericCellValue(), equalTo(3.12312312312));
assertThat(contents.get(1).get(1).getStringCellValue(), equalTo("1,023,042"));
assertThat(contents.get(1).get(1).getNumericCellValue(), equalTo(1023042.0));
assertThat(contents.get(1).get(2).getStringCellValue(), equalTo("-312,231.12"));
assertThat(contents.get(1).get(2).getNumericCellValue(), equalTo(-312231.12123145));
assertThat(contents.get(1).get(3).getStringCellValue(), equalTo("(132)"));
assertThat(contents.get(1).get(3).getNumericCellValue(), equalTo(-132.0));
}
#location 21
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.