task_id
stringlengths
5
19
buggy_code
stringlengths
44
3.26k
fixed_code
stringlengths
67
3.31k
file_path
stringlengths
36
95
issue_title
stringlengths
0
150
issue_description
stringlengths
0
2.85k
start_line
int64
9
4.43k
end_line
int64
11
4.52k
Closure-92
void replace() { if (firstNode == null) { // Don't touch the base case ('goog'). replacementNode = candidateDefinition; return; } // Handle the case where there is a duplicate definition for an explicitly // provided symbol. if (candidateDefinition != null && explicitNode != null) { explicitN...
void replace() { if (firstNode == null) { // Don't touch the base case ('goog'). replacementNode = candidateDefinition; return; } // Handle the case where there is a duplicate definition for an explicitly // provided symbol. if (candidateDefinition != null && explicitNode != null) { explicitN...
src/com/google/javascript/jscomp/ProcessClosurePrimitives.java
bug with implicit namespaces across modules
If there are three modules, the latter two of which depend on the root module: // Module A goog.provide('apps'); // Module B goog.provide('apps.foo.bar.B'); // Module C goog.provide('apps.foo.bar.C'); and this is compiled in SIMPLE_OPTIMIZATIONS mode, the following code will be produced: // Module A var a...
747
809
Closure-94
static boolean isValidDefineValue(Node val, Set<String> defines) { switch (val.getType()) { case Token.STRING: case Token.NUMBER: case Token.TRUE: case Token.FALSE: return true; // Binary operators are only valid if both children are valid. case Token.BITAND: case Token.BITNOT: ...
static boolean isValidDefineValue(Node val, Set<String> defines) { switch (val.getType()) { case Token.STRING: case Token.NUMBER: case Token.TRUE: case Token.FALSE: return true; // Binary operators are only valid if both children are valid. case Token.ADD: case Token.BITAND: cas...
src/com/google/javascript/jscomp/NodeUtil.java
closure-compiler @define annotation does not allow line to be split on 80 characters.
What steps will reproduce the problem? 1. Create a JavaScript file with the followiing: /** @define {string} */ var CONSTANT = "some very long string name that I want to wrap " + "and so break using a + since I don't want to " + "introduce a newline into the string." 2. Run closure-...
320
347
Closure-96
private void visitParameterList(NodeTraversal t, Node call, FunctionType functionType) { Iterator<Node> arguments = call.children().iterator(); arguments.next(); // skip the function name Iterator<Node> parameters = functionType.getParameters().iterator(); int ordinal = 0; Node parameter = null; Node a...
private void visitParameterList(NodeTraversal t, Node call, FunctionType functionType) { Iterator<Node> arguments = call.children().iterator(); arguments.next(); // skip the function name Iterator<Node> parameters = functionType.getParameters().iterator(); int ordinal = 0; Node parameter = null; Node a...
src/com/google/javascript/jscomp/TypeCheck.java
Missing type-checks for var_args notation
What steps will reproduce the problem? 1. Compile this: //------------------------------------- // ==ClosureCompiler== // @compilation_level SIMPLE_OPTIMIZATIONS // @warning_level VERBOSE // @output_file_name default.js // @formatting pretty_print // ==/ClosureCompiler== /** * @param {...string} var_args */ ...
1,399
1,430
Closure-97
private Node tryFoldShift(Node n, Node left, Node right) { if (left.getType() == Token.NUMBER && right.getType() == Token.NUMBER) { double result; double lval = left.getDouble(); double rval = right.getDouble(); // check ranges. We do not do anything that would clip the double to // a 32-...
private Node tryFoldShift(Node n, Node left, Node right) { if (left.getType() == Token.NUMBER && right.getType() == Token.NUMBER) { double result; double lval = left.getDouble(); double rval = right.getDouble(); // check ranges. We do not do anything that would clip the double to // a 32-...
src/com/google/javascript/jscomp/PeepholeFoldConstants.java
Unsigned Shift Right (>>>) bug operating on negative numbers
What steps will reproduce the problem? i = -1 >>> 0 ; What is the expected output? What do you see instead? Expected: i = -1 >>> 0 ; // or // i = 4294967295 ; Instead: i = -1 ; What version of the product are you using? On what operating system? The UI version as of 7/18/2001 (http://closure-compiler.appspot.com/...
652
713
Closure-99
public boolean shouldTraverse(NodeTraversal t, Node n, Node parent) { if (n.getType() == Token.FUNCTION) { // Don't traverse functions that are constructors or have the @this // or @override annotation. JSDocInfo jsDoc = getFunctionJsDocInfo(n); if (jsDoc != null && (jsDoc.isConstructor() || ...
public boolean shouldTraverse(NodeTraversal t, Node n, Node parent) { if (n.getType() == Token.FUNCTION) { // Don't traverse functions that are constructors or have the @this // or @override annotation. JSDocInfo jsDoc = getFunctionJsDocInfo(n); if (jsDoc != null && (jsDoc.isConstructor() || ...
src/com/google/javascript/jscomp/CheckGlobalThis.java
Prototypes declared with quotes produce a JSC_USED_GLOBAL_THIS warning.
Compiling the following code (in advanced optimizations with VERBOSE warning levels): /** @constructor */ function MyClass() {} MyClass.prototype["MyMethod"] = function(a) { this.a = a; } window["MyClass"] = MyClass; Results in the following warning: "dangerous use of the global this object." This notation...
84
136
Codec-15
private char getMappingCode(final String str, final int index) { // map() throws IllegalArgumentException final char mappedChar = this.map(str.charAt(index)); // HW rule check if (index > 1 && mappedChar != '0') { final char hwChar = str.charAt(index - 1); if ('H' == hwChar || 'W' == hwC...
private char getMappingCode(final String str, final int index) { // map() throws IllegalArgumentException final char mappedChar = this.map(str.charAt(index)); // HW rule check if (index > 1 && mappedChar != '0') { for (int i=index-1 ; i>=0 ; i--) { final char prevChar = str.charAt(i)...
src/main/java/org/apache/commons/codec/language/Soundex.java
Bug in HW rule in Soundex
The Soundex algorithm says that if two characters that map to the same code are separated by H or W, the second one is not encoded. However, in the implementation (in Soundex.getMappingCode() line 191), a character that is preceded by two characters that are either H or W, is not encoded, regardless of what the last co...
183
198
Codec-17
public static String newStringIso8859_1(final byte[] bytes) { return new String(bytes, Charsets.ISO_8859_1); }
public static String newStringIso8859_1(final byte[] bytes) { return newString(bytes, Charsets.ISO_8859_1); }
src/main/java/org/apache/commons/codec/binary/StringUtils.java
StringUtils.newStringxxx(null) should return null, not NPE
Method calls such as StringUtils.newStringIso8859_1(null) should return null, not NPE. It looks like this capability was lost with the fix for CODEC-136, i.e. http://svn.apache.org/viewvc?rev=1306366&view=rev Several methods were changed from return StringUtils.newString(bytes, CharEncoding.xxx); to return new String(...
338
340
Codec-18
public static boolean equals(final CharSequence cs1, final CharSequence cs2) { if (cs1 == cs2) { return true; } if (cs1 == null || cs2 == null) { return false; } if (cs1 instanceof String && cs2 instanceof String) { return cs1.equals(cs2); } return CharSequenceUtils.r...
public static boolean equals(final CharSequence cs1, final CharSequence cs2) { if (cs1 == cs2) { return true; } if (cs1 == null || cs2 == null) { return false; } if (cs1 instanceof String && cs2 instanceof String) { return cs1.equals(cs2); } return cs1.length() == cs2...
src/main/java/org/apache/commons/codec/binary/StringUtils.java
StringUtils.equals(CharSequence cs1, CharSequence cs2) can fail with String Index OBE
StringUtils.equals(CharSequence cs1, CharSequence cs2) fails with String Index OBE if the two sequences are different lengths.
71
82
Codec-2
void encode(byte[] in, int inPos, int inAvail) { if (eof) { return; } // inAvail < 0 is how we're informed of EOF in the underlying data we're // encoding. if (inAvail < 0) { eof = true; if (buf == null || buf.length - pos < encodeSize) { resizeBuf(); } ...
void encode(byte[] in, int inPos, int inAvail) { if (eof) { return; } // inAvail < 0 is how we're informed of EOF in the underlying data we're // encoding. if (inAvail < 0) { eof = true; if (buf == null || buf.length - pos < encodeSize) { resizeBuf(); } ...
src/java/org/apache/commons/codec/binary/Base64.java
Base64 bug with empty input (new byte[0])
Base64.encode(new byte[0]) doesn't return an empty byte array back! It returns CRLF.
414
473
Codec-6
public int read(byte b[], int offset, int len) throws IOException { if (b == null) { throw new NullPointerException(); } else if (offset < 0 || len < 0) { throw new IndexOutOfBoundsException(); } else if (offset > b.length || offset + len > b.length) { throw new IndexOutOfBoundsExcep...
public int read(byte b[], int offset, int len) throws IOException { if (b == null) { throw new NullPointerException(); } else if (offset < 0 || len < 0) { throw new IndexOutOfBoundsException(); } else if (offset > b.length || offset + len > b.length) { throw new IndexOutOfBoundsExcep...
src/java/org/apache/commons/codec/binary/Base64InputStream.java
Base64InputStream#read(byte[]) incorrectly returns 0 at end of any stream which is multiple of 3 bytes long
Using new InputStreamReader(new Base64InputStream(in, true)) sometimes fails with "java.io.IOException: Underlying input stream returned zero bytes". This is been tracked down that Base64InputStream#read(byte[]) incorrectly returns 0 at end of any stream which is multiple of 3 bytes long.
138
180
Codec-7
public static String encodeBase64String(byte[] binaryData) { return StringUtils.newStringUtf8(encodeBase64(binaryData, true)); }
public static String encodeBase64String(byte[] binaryData) { return StringUtils.newStringUtf8(encodeBase64(binaryData, false)); }
src/java/org/apache/commons/codec/binary/Base64.java
Base64.encodeBase64String() shouldn't chunk
Base64.encodeBase64String() shouldn't chunk. Change this: public static String encodeBase64String(byte[] binaryData) { return StringUtils.newStringUtf8(encodeBase64(binaryData, true)); } To this: public static String encodeBase64String(byte[] binaryData) { return StringUtils.newStringUtf8(encodeBase64(binary...
669
671
Codec-9
public static byte[] encodeBase64(byte[] binaryData, boolean isChunked, boolean urlSafe, int maxResultSize) { if (binaryData == null || binaryData.length == 0) { return binaryData; } long len = getEncodeLength(binaryData, MIME_CHUNK_SIZE, CHUNK_SEPARATOR); if (len > maxResultSize) { thr...
public static byte[] encodeBase64(byte[] binaryData, boolean isChunked, boolean urlSafe, int maxResultSize) { if (binaryData == null || binaryData.length == 0) { return binaryData; } long len = getEncodeLength(binaryData, isChunked ? MIME_CHUNK_SIZE : 0, CHUNK_SEPARATOR); if (len > maxResultSiz...
src/java/org/apache/commons/codec/binary/Base64.java
Base64.encodeBase64(byte[] binaryData, boolean isChunked, boolean urlSafe, int maxResultSize) throws IAE for valid maxResultSize if isChunked is false
If isChunked is false, Base64.encodeBase64(byte[] binaryData, boolean isChunked, boolean urlSafe, int maxResultSize) throws IAE for valid maxResultSize. Test case and fix will be applied shortly.
822
837
Collections-26
private Object readResolve() { calculateHashCode(keys); return this; }
protected Object readResolve() { calculateHashCode(keys); return this; }
src/main/java/org/apache/commons/collections4/keyvalue/MultiKey.java
MultiKey subclassing has deserialization problem since COLLECTIONS-266: either declare protected readResolve() or MultiKey must be final
MultiKey from collections 4 provides a transient hashCode and a private readResolve to resolve COLLECTIONS-266: Issue with MultiKey when serialized/deserialized via RMI. Unfortunately the solution does not work in case of subclassing: readResolve in MultiKey should be declared protected readResolve() to be called durin...
277
280
Compress-1
public void close() throws IOException { if (!this.closed) { super.close(); this.closed = true; } }
public void close() throws IOException { if (!this.closed) { this.finish(); super.close(); this.closed = true; } }
src/main/java/org/apache/commons/compress/archivers/cpio/CpioArchiveOutputStream.java
CPIO reports unexpected EOF
When unpacking an CPIO archive (made with the compress classes or even made with OSX cpio comandline tool) an EOF exception is thrown. Here is the testcode: final File input = getFile("cmdcreated.cpio"); final InputStream in = new FileInputStream(input); CpioArchiveInputStream cin = new CpioArch...
344
349
Compress-10
private void resolveLocalFileHeaderData(Map<ZipArchiveEntry, NameAndComment> entriesWithoutUTF8Flag) throws IOException { // changing the name of a ZipArchiveEntry is going to change // the hashcode - see COMPRESS-164 // Map needs to be reconstructed in order to k...
private void resolveLocalFileHeaderData(Map<ZipArchiveEntry, NameAndComment> entriesWithoutUTF8Flag) throws IOException { // changing the name of a ZipArchiveEntry is going to change // the hashcode - see COMPRESS-164 // Map needs to be reconstructed in order to k...
src/main/java/org/apache/commons/compress/archivers/zip/ZipFile.java
Cannot Read Winzip Archives With Unicode Extra Fields
I have a zip file created with WinZip containing Unicode extra fields. Upon attempting to extract it with org.apache.commons.compress.archivers.zip.ZipFile, ZipFile.getInputStream() returns null for ZipArchiveEntries previously retrieved with ZipFile.getEntry() or even ZipFile.getEntries(). See UTF8ZipFilesTest.patch i...
801
843
Compress-11
public ArchiveInputStream createArchiveInputStream(final InputStream in) throws ArchiveException { if (in == null) { throw new IllegalArgumentException("Stream must not be null."); } if (!in.markSupported()) { throw new IllegalArgumentException("Mark is not supported."); } ...
public ArchiveInputStream createArchiveInputStream(final InputStream in) throws ArchiveException { if (in == null) { throw new IllegalArgumentException("Stream must not be null."); } if (!in.markSupported()) { throw new IllegalArgumentException("Mark is not supported."); } ...
src/main/java/org/apache/commons/compress/archivers/ArchiveStreamFactory.java
createArchiveInputStream detects text files less than 100 bytes as tar archives
The fix for COMPRESS-117 which modified ArchiveStreamFactory().createArchiveInputStream(inputstream) results in short text files (empirically seems to be those <= 100 bytes) being detected as tar archives which obviously is not desirable if one wants to know whether or not the files are archives. I'm not an expert on c...
197
254
Compress-13
protected void setName(String name) { this.name = name; }
protected void setName(String name) { if (name != null && getPlatform() == PLATFORM_FAT && name.indexOf("/") == -1) { name = name.replace('\\', '/'); } this.name = name; }
src/main/java/org/apache/commons/compress/archivers/zip/ZipArchiveEntry.java
ArchiveInputStream#getNextEntry(): Problems with WinZip directories with Umlauts
There is a problem when handling a WinZip-created zip with Umlauts in directories. I'm accessing a zip file created with WinZip containing a directory with an umlaut ("ä") with ArchiveInputStream. When creating the zip file the unicode-flag of winzip had been active. The following problem occurs when accessing the entr...
511
513
Compress-15
public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } ZipArchiveEntry other = (ZipArchiveEntry) obj; String myName = getName(); String otherName = other.getName(); if (myName == null) { ...
public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } ZipArchiveEntry other = (ZipArchiveEntry) obj; String myName = getName(); String otherName = other.getName(); if (myName == null) { ...
src/main/java/org/apache/commons/compress/archivers/zip/ZipArchiveEntry.java
ZipArchiveInputStream and ZipFile don't produce equals ZipArchiveEntry instances
I'm trying to use a ZipArchiveEntry coming from ZipArchiveInputStream that I stored somwhere for later with a ZipFile and it does not work. The reason is that it can't find the ZipArchiveEntry in the ZipFile entries map. It is exactly the same zip file but both entries are not equals so the Map#get fail. As far as I ca...
649
688
Compress-16
public ArchiveInputStream createArchiveInputStream(final InputStream in) throws ArchiveException { if (in == null) { throw new IllegalArgumentException("Stream must not be null."); } if (!in.markSupported()) { throw new IllegalArgumentException("Mark is not supported."); } ...
public ArchiveInputStream createArchiveInputStream(final InputStream in) throws ArchiveException { if (in == null) { throw new IllegalArgumentException("Stream must not be null."); } if (!in.markSupported()) { throw new IllegalArgumentException("Mark is not supported."); } ...
src/main/java/org/apache/commons/compress/archivers/ArchiveStreamFactory.java
Too relaxed tar detection in ArchiveStreamFactory
The relaxed tar detection logic added in COMPRESS-117 unfortunately matches also some non-tar files like a test AIFF file that Apache Tika uses. It would be good to improve the detection heuristics to still match files like the one in COMPRESS-117 but avoid false positives like the AIFF file in Tika.
197
258
Compress-17
public static long parseOctal(final byte[] buffer, final int offset, final int length) { long result = 0; int end = offset + length; int start = offset; if (length < 2){ throw new IllegalArgumentException("Length "+length+" must be at least 2"); } if (buffer[start] == 0) { ...
public static long parseOctal(final byte[] buffer, final int offset, final int length) { long result = 0; int end = offset + length; int start = offset; if (length < 2){ throw new IllegalArgumentException("Length "+length+" must be at least 2"); } if (buffer[start] == 0) { ...
src/main/java/org/apache/commons/compress/archivers/tar/TarUtils.java
Tar file for Android backup cannot be read
Attached tar file was generated by some kind of backup tool on Android. Normal tar utilities seem to handle it fine, but Commons Compress doesn't. java.lang.IllegalArgumentException: Invalid byte 0 at offset 5 in '01750{NUL}{NUL}{NUL}' len=8 at org.apache.commons.compress.archivers.tar.TarUtils.parseOctal(TarUtils...
102
151
Compress-19
public void reparseCentralDirectoryData(boolean hasUncompressedSize, boolean hasCompressedSize, boolean hasRelativeHeaderOffset, boolean hasDiskStart) throws ZipException { if (rawCentralDirec...
public void reparseCentralDirectoryData(boolean hasUncompressedSize, boolean hasCompressedSize, boolean hasRelativeHeaderOffset, boolean hasDiskStart) throws ZipException { if (rawCentralDirec...
src/main/java/org/apache/commons/compress/archivers/zip/Zip64ExtendedInformationExtraField.java
ZipException on reading valid zip64 file
ZipFile zip = new ZipFile(new File("ordertest-64.zip")); throws ZipException "central directory zip64 extended information extra field's length doesn't match central directory data. Expected length 16 but is 28". The archive was created by using DotNetZip-WinFormsTool uzing zip64 flag (forces always to make zip64 arch...
249
287
Compress-21
private void writeBits(final DataOutput header, final BitSet bits, final int length) throws IOException { int cache = 0; int shift = 7; for (int i = 0; i < length; i++) { cache |= ((bits.get(i) ? 1 : 0) << shift); --shift; if (shift == 0) { header.write(cache); ...
private void writeBits(final DataOutput header, final BitSet bits, final int length) throws IOException { int cache = 0; int shift = 7; for (int i = 0; i < length; i++) { cache |= ((bits.get(i) ? 1 : 0) << shift); if (--shift < 0) { header.write(cache); shift = 7; ...
src/main/java/org/apache/commons/compress/archivers/sevenz/SevenZOutputFile.java
Writing 7z empty entries produces incorrect or corrupt archive
I couldn't find an exact rule that causes this incorrect behavior, but I tried to reduce it to some simple scenarios to reproduce it: Input: A folder with certain files -> tried to archive it. If the folder contains more than 7 files the incorrect behavior appears. Scenario 1: 7 empty files Result: The created archive ...
634
649
Compress-23
InputStream decode(final InputStream in, final Coder coder, byte[] password) throws IOException { byte propsByte = coder.properties[0]; long dictSize = coder.properties[1]; for (int i = 1; i < 4; i++) { dictSize |= (coder.properties[i + 1] << (8 * i)); } if (dictSize > LZMAInputStrea...
InputStream decode(final InputStream in, final Coder coder, byte[] password) throws IOException { byte propsByte = coder.properties[0]; long dictSize = coder.properties[1]; for (int i = 1; i < 4; i++) { dictSize |= (coder.properties[i + 1] & 0xffl) << (8 * i); } if (dictSize > LZMAIn...
src/main/java/org/apache/commons/compress/archivers/sevenz/Coders.java
7z: 16 MB dictionary is too big
I created an archiv with 7zip 9.20 containing the compress-1.7-src directory. Also tried it with 1.6 version and directory. I downloaded the zip file and reziped it as 7z. The standard setting where used: Compression level: normal Compression method: lzma2 Dictionary size: 16 MB Word size: 32 Solid Block size: 2 GB I ...
107
118
Compress-24
public static long parseOctal(final byte[] buffer, final int offset, final int length) { long result = 0; int end = offset + length; int start = offset; if (length < 2){ throw new IllegalArgumentException("Length "+length+" must be at least 2"); } if (buffer[start] == 0) { ...
public static long parseOctal(final byte[] buffer, final int offset, final int length) { long result = 0; int end = offset + length; int start = offset; if (length < 2){ throw new IllegalArgumentException("Length "+length+" must be at least 2"); } if (buffer[start] == 0) { ...
src/main/java/org/apache/commons/compress/archivers/tar/TarUtils.java
TarArchiveInputStream fails to read entry with big user-id value
Caused by: java.lang.IllegalArgumentException: Invalid byte 52 at offset 7 in '62410554' len=8 at org.apache.commons.compress.archivers.tar.TarUtils.parseOctal(TarUtils.java:130) at org.apache.commons.compress.archivers.tar.TarUtils.parseOctalOrBinary(TarUtils.java:175) at org.apache.commons.compress.archivers.tar.T...
102
153
Compress-26
public static long skip(InputStream input, long numToSkip) throws IOException { long available = numToSkip; while (numToSkip > 0) { long skipped = input.skip(numToSkip); if (skipped == 0) { break; } numToSkip -= skipped; } return available - numToSkip...
public static long skip(InputStream input, long numToSkip) throws IOException { long available = numToSkip; while (numToSkip > 0) { long skipped = input.skip(numToSkip); if (skipped == 0) { break; } numToSkip -= skipped; } if (numToSkip > 0) { ...
src/main/java/org/apache/commons/compress/utils/IOUtils.java
IOUtils.skip does not work as advertised
I am trying to feed a TarInputStream from a CipherInputStream. It does not work, because IOUtils.skip() does not adhere to the contract it claims in javadoc: " * <p>This method will only skip less than the requested number of bytes if the end of the input stream has been reached.</p>" However it does: ...
94
105
Compress-28
public int read(byte[] buf, int offset, int numToRead) throws IOException { int totalRead = 0; if (hasHitEOF || entryOffset >= entrySize) { return -1; } if (currEntry == null) { throw new IllegalStateException("No current tar entry"); } numToRead = Math.min(numToRead, available()...
public int read(byte[] buf, int offset, int numToRead) throws IOException { int totalRead = 0; if (hasHitEOF || entryOffset >= entrySize) { return -1; } if (currEntry == null) { throw new IllegalStateException("No current tar entry"); } numToRead = Math.min(numToRead, available()...
src/main/java/org/apache/commons/compress/archivers/tar/TarArchiveInputStream.java
TarArchiveInputStream silently finished when unexpected EOF occured
I just found the following test case didn't raise an IOException as it used to be for a tar trimmed on purpose @Test public void testCorruptedBzip2() throws IOException { String archivePath = PathUtil.join(testdataDir, "test.tar.bz2"); TarArchiveInputStream input = null; input = new TarArchiveInputStream...
569
592
Compress-30
public int read(final byte[] dest, final int offs, final int len) throws IOException { if (offs < 0) { throw new IndexOutOfBoundsException("offs(" + offs + ") < 0."); } if (len < 0) { throw new IndexOutOfBoundsException("len(" + len + ") < 0."); } if (offs + len > dest.length) { ...
public int read(final byte[] dest, final int offs, final int len) throws IOException { if (offs < 0) { throw new IndexOutOfBoundsException("offs(" + offs + ") < 0."); } if (len < 0) { throw new IndexOutOfBoundsException("len(" + len + ") < 0."); } if (offs + len > dest.length) { ...
src/main/java/org/apache/commons/compress/compressors/bzip2/BZip2CompressorInputStream.java
BZip2CompressorInputStream return value wrong when told to read to a full buffer.
BZip2CompressorInputStream.read(buffer, offset, length) returns -1 when given an offset equal to the length of the buffer. This indicates, not that the buffer was full, but that the stream was finished. It seems like a pretty stupid thing to do - but I'm getting this when trying to use Kryo serialization (which is prob...
153
179
Compress-35
public static boolean verifyCheckSum(byte[] header) { long storedSum = 0; long unsignedSum = 0; long signedSum = 0; int digits = 0; for (int i = 0; i < header.length; i++) { byte b = header[i]; if (CHKSUM_OFFSET <= i && i < CHKSUM_OFFSET + CHKSUMLEN) { if ('0' <= b && b...
public static boolean verifyCheckSum(byte[] header) { long storedSum = parseOctal(header, CHKSUM_OFFSET, CHKSUMLEN); long unsignedSum = 0; long signedSum = 0; int digits = 0; for (int i = 0; i < header.length; i++) { byte b = header[i]; if (CHKSUM_OFFSET <= i && i < CHKSUM_OFFSET +...
src/main/java/org/apache/commons/compress/archivers/tar/TarUtils.java
TAR checksum fails when checksum is right aligned
The linked TAR has a checksum with zero padding on the left instead of the expected NULL-SPACE terminator on the right. As a result the last two digits of the stored checksum are lost and the otherwise valid checksum is treated as invalid. Given that the code already checks for digits being in range before adding them ...
593
613
Compress-36
private InputStream getCurrentStream() throws IOException { if (deferredBlockStreams.isEmpty()) { throw new IllegalStateException("No current 7z entry (call getNextEntry() first)."); } while (deferredBlockStreams.size() > 1) { // In solid compression mode we need to decompress all leadi...
private InputStream getCurrentStream() throws IOException { if (archive.files[currentEntryIndex].getSize() == 0) { return new ByteArrayInputStream(new byte[0]); } if (deferredBlockStreams.isEmpty()) { throw new IllegalStateException("No current 7z entry (call getNextEntry() first)."); } ...
src/main/java/org/apache/commons/compress/archivers/sevenz/SevenZFile.java
Calling SevenZFile.read() on empty SevenZArchiveEntry throws IllegalStateException
I'm pretty sure COMPRESS-340 breaks reading empty archive entries. When calling getNextEntry() and that entry has no content, the code jumps into the first block at line 830 (SevenZFile.class), clearing the deferredBlockStreams. When calling entry.read(...) afterwards an IllegalStateException ("No current 7z entry (cal...
901
916
Compress-37
Map<String, String> parsePaxHeaders(final InputStream i) throws IOException { final Map<String, String> headers = new HashMap<String, String>(globalPaxHeaders); // Format is "length keyword=value\n"; while(true){ // get length int ch; int len = 0; int read = 0; while((ch ...
Map<String, String> parsePaxHeaders(final InputStream i) throws IOException { final Map<String, String> headers = new HashMap<String, String>(globalPaxHeaders); // Format is "length keyword=value\n"; while(true){ // get length int ch; int len = 0; int read = 0; while((ch ...
src/main/java/org/apache/commons/compress/archivers/tar/TarArchiveInputStream.java
Parsing PAX headers fails with NegativeArraySizeException
The TarArchiveInputStream.parsePaxHeaders method fails with a NegativeArraySizeException when there is an empty line at the end of the headers. The inner loop starts reading the length, but it gets a newline (10) and ends up subtracting '0' (48) from it; the result is a negative length that blows up an attempt to alloc...
452
502
Compress-38
public boolean isDirectory() { if (file != null) { return file.isDirectory(); } if (linkFlag == LF_DIR) { return true; } if (getName().endsWith("/")) { return true; } return false; }
public boolean isDirectory() { if (file != null) { return file.isDirectory(); } if (linkFlag == LF_DIR) { return true; } if (!isPaxHeader() && !isGlobalPaxHeader() && getName().endsWith("/")) { return true; } return false; }
src/main/java/org/apache/commons/compress/archivers/tar/TarArchiveEntry.java
PAX header entry name ending with / causes problems
There seems to be a problem when a PAX header entry (link flag is 'x') has a name ending with "/". The TarArchiveEntry.isDirectory() check ends up returning true because of the trailing slash which means no content can be read from the entry. PAX header parsing effectively finds nothing and the stream is not advanced; ...
850
864
Compress-39
public static String sanitize(String s) { final char[] chars = s.toCharArray(); final int len = chars.length; final StringBuilder sb = new StringBuilder(); for (int i = 0; i < len; i++) { final char c = chars[i]; if (!Character.isISOControl(c)) { C...
public static String sanitize(String s) { final char[] cs = s.toCharArray(); final char[] chars = cs.length <= MAX_SANITIZED_NAME_LENGTH ? cs : Arrays.copyOf(cs, MAX_SANITIZED_NAME_LENGTH); if (cs.length > MAX_SANITIZED_NAME_LENGTH) { for (int i = MAX_SANITIZED_NAME_LENGTH - 3; i < M...
src/main/java/org/apache/commons/compress/utils/ArchiveUtils.java
Defective .zip-archive produces problematic error message
A truncated .zip-File produces an java.io.EOFException conatining a hughe amount of byte[]-data in the error-message - leading to beeps and crippeling workload in an potential console-logger.
272
288
Compress-40
public long readBits(final int count) throws IOException { if (count < 0 || count > MAXIMUM_CACHE_SIZE) { throw new IllegalArgumentException("count must not be negative or greater than " + MAXIMUM_CACHE_SIZE); } while (bitsCachedSize < count) { final long nextByte = in.read(); if (ne...
public long readBits(final int count) throws IOException { if (count < 0 || count > MAXIMUM_CACHE_SIZE) { throw new IllegalArgumentException("count must not be negative or greater than " + MAXIMUM_CACHE_SIZE); } while (bitsCachedSize < count && bitsCachedSize < 57) { final long nextByte = in...
src/main/java/org/apache/commons/compress/utils/BitInputStream.java
Overflow in BitInputStream
in Class BitInputStream.java(\src\main\java\org\apache\commons\compress\utils), funcion: public long readBits(final int count) throws IOException { if (count < 0 || count > MAXIMUM_CACHE_SIZE) { throw new IllegalArgumentException("count must not be negative or greater than " + MAXIMUM_CACHE_SIZE);...
81
109
Compress-44
public ChecksumCalculatingInputStream(final Checksum checksum, final InputStream in) { this.checksum = checksum; this.in = in; }
public ChecksumCalculatingInputStream(final Checksum checksum, final InputStream in) { if ( checksum == null ){ throw new NullPointerException("Parameter checksum must not be null"); } if ( in == null ){ throw new NullPointerException("Parameter in must not be null"); } this.check...
src/main/java/org/apache/commons/compress/utils/ChecksumCalculatingInputStream.java
NullPointerException defect in ChecksumCalculatingInputStream#getValue()
NullPointerException defect in ChecksumCalculatingInputStream#getValue() detected as stated in pull request 33: https://github.com/apache/commons-compress/pull/33 Furthermore the following test describes the problem: @Test(expected = NullPointerException.class) //I assume this behaviour to be a bug or at least a d...
33
39
Compress-45
public static int formatLongOctalOrBinaryBytes( final long value, final byte[] buf, final int offset, final int length) { // Check whether we are dealing with UID/GID or SIZE field final long maxAsOctalChar = length == TarConstants.UIDLEN ? TarConstants.MAXID : TarConstants.MAXSIZE; final boolean nega...
public static int formatLongOctalOrBinaryBytes( final long value, final byte[] buf, final int offset, final int length) { // Check whether we are dealing with UID/GID or SIZE field final long maxAsOctalChar = length == TarConstants.UIDLEN ? TarConstants.MAXID : TarConstants.MAXSIZE; final boolean nega...
src/main/java/org/apache/commons/compress/archivers/tar/TarUtils.java
TarUtils.formatLongOctalOrBinaryBytes never uses result of formatLongBinary
if the length < 9, formatLongBinary is executed, then overwritten by the results of formatBigIntegerBinary. If the results are not ignored, a unit test would fail. Also, do the binary hacks need to support negative numbers?
474
492
Compress-46
private static ZipLong unixTimeToZipLong(long l) { final long TWO_TO_32 = 0x100000000L; if (l >= TWO_TO_32) { throw new IllegalArgumentException("X5455 timestamps must fit in a signed 32 bit integer: " + l); } return new ZipLong(l); }
private static ZipLong unixTimeToZipLong(long l) { if (l < Integer.MIN_VALUE || l > Integer.MAX_VALUE) { throw new IllegalArgumentException("X5455 timestamps must fit in a signed 32 bit integer: " + l); } return new ZipLong(l); }
src/main/java/org/apache/commons/compress/archivers/zip/X5455_ExtendedTimestamp.java
Tests failing under jdk 9 : one reflection issue, one change to ZipEntry related issue
X5455_ExtendedTimestampTest is failing under JDK 9 , due to what appears to be a bogus value returned from getTime(). It seems like the test failure might be due to the changes introduced for this: https://bugs.openjdk.java.net/browse/JDK-8073497 Tests were run using intelliJ TestRunner, using the openjdk9 build from...
528
534
Compress-5
public int read(byte[] buffer, int start, int length) throws IOException { if (closed) { throw new IOException("The stream is closed"); } if (inf.finished() || current == null) { return -1; } // avoid int overflow, check null buffer if (start <= buffer.length && length >= 0 && s...
public int read(byte[] buffer, int start, int length) throws IOException { if (closed) { throw new IOException("The stream is closed"); } if (inf.finished() || current == null) { return -1; } // avoid int overflow, check null buffer if (start <= buffer.length && length >= 0 && s...
src/main/java/org/apache/commons/compress/archivers/zip/ZipArchiveInputStream.java
ZipArchiveInputStream doesn't report the end of a truncated archive
If a Zip archive is truncated, (e.g. because it is the first volume in a multi-volume archive) the ZipArchiveInputStream.read() method will not detect that fact. All calls to read() will return 0 bytes read. They will not return -1 (end of stream), nor will they throw any exception (which would seem like a good idea to...
191
246
Compress-7
public static String parseName(byte[] buffer, final int offset, final int length) { StringBuffer result = new StringBuffer(length); int end = offset + length; for (int i = offset; i < end; ++i) { if (buffer[i] == 0) { break; } result.append((char) buffer[i]); ...
public static String parseName(byte[] buffer, final int offset, final int length) { StringBuffer result = new StringBuffer(length); int end = offset + length; for (int i = offset; i < end; ++i) { byte b = buffer[i]; if (b == 0) { // Trailing null break; } ...
src/main/java/org/apache/commons/compress/archivers/tar/TarUtils.java
TarUtils.parseName does not properly handle characters outside the range 0-127
if a tarfile contains files with special characters, the names of the tar entries are wrong. example: correct name: 0302-0601-3±±±F06±W220±ZB±LALALA±±±±±±±±±±CAN±±DC±±±04±060302±MOE.model name resolved by TarUtils.parseName: 0302-0101-3ᄆᄆᄆF06ᄆW220ᄆZBᄆHECKMODULᄆᄆᄆᄆᄆᄆᄆᄆᄆᄆECEᄆᄆDCᄆᄆᄆ07ᄆ060302ᄆDOERN.model please use: resul...
93
105
Compress-8
public static long parseOctal(final byte[] buffer, final int offset, final int length) { long result = 0; boolean stillPadding = true; int end = offset + length; int start = offset; for (int i = start; i < end; i++){ final byte currentByte = buffer[i]; if (currentByte == ...
public static long parseOctal(final byte[] buffer, final int offset, final int length) { long result = 0; int end = offset + length; int start = offset; if (length < 2){ throw new IllegalArgumentException("Length "+length+" must be at least 2"); } boolean allNUL = true; ...
src/main/java/org/apache/commons/compress/archivers/tar/TarUtils.java
TarArchiveEntry.parseTarHeader() includes the trailing space/NUL when parsing the octal size
TarArchiveEntry.parseTarHeader() includes the trailing space/NUL when parsing the octal size. Although the size field in the header is 12 bytes, the last byte is supposed to be space or NUL - i.e. only 11 octal digits are allowed for the size.
51
87
Csv-1
public int read() throws IOException { int current = super.read(); if (current == '\n') { lineCounter++; } lastChar = current; return lastChar; }
public int read() throws IOException { int current = super.read(); if (current == '\r' || (current == '\n' && lastChar != '\r')) { lineCounter++; } lastChar = current; return lastChar; }
src/main/java/org/apache/commons/csv/ExtendedBufferedReader.java
ExtendedBufferReader does not handle EOL consistently
ExtendedBufferReader checks for '\n' (LF) in the read() methods, incrementing linecount when found. However, the readLine() method calls BufferedReader.readLine() which treats CR, LF and CRLF equally (and drops them). If the code is to be flexible in what it accepts, the class should also allow for CR alone as a line t...
56
63
Csv-10
public CSVPrinter(final Appendable out, final CSVFormat format) throws IOException { Assertions.notNull(out, "out"); Assertions.notNull(format, "format"); this.out = out; this.format = format; this.format.validate(); // TODO: Is it a good idea to do this here instead of on the first call to a p...
public CSVPrinter(final Appendable out, final CSVFormat format) throws IOException { Assertions.notNull(out, "out"); Assertions.notNull(format, "format"); this.out = out; this.format = format; this.format.validate(); // TODO: Is it a good idea to do this here instead of on the first call to a p...
src/main/java/org/apache/commons/csv/CSVPrinter.java
CSVFormat#withHeader doesn't work with CSVPrinter
In the current version CSVFormat#withHeader is only used by CSVParser. It would be nice if CSVPrinter also supported it. Ideally, the following line of code CSVPrinter csvPrinter = CSVFormat.TDF .withHeader("x") .print(Files.newBufferedWriter(Paths.get("data.csv"))); csvPrinter.printRecord(42); csvPrinter.cl...
61
70
Csv-2
public String get(final String name) { if (mapping == null) { throw new IllegalStateException( "No header mapping was specified, the record values can't be accessed by name"); } final Integer index = mapping.get(name); return index != null ? values[index.intValue()] : null; }
public String get(final String name) { if (mapping == null) { throw new IllegalStateException( "No header mapping was specified, the record values can't be accessed by name"); } final Integer index = mapping.get(name); try { return index != null ? values[index.intValue()]...
src/main/java/org/apache/commons/csv/CSVRecord.java
CSVRecord does not verify that the length of the header mapping matches the number of values
CSVRecord does not verify that the size of the header mapping matches the number of values. The following test will produce a ArrayOutOfBoundsException: @Test public void testInvalidHeaderTooLong() throws Exception { final CSVParser parser = new CSVParser("a,b", CSVFormat.newBuilder().withHeader("A", "B", "C").buil...
79
86
Csv-3
int readEscape() throws IOException { // the escape char has just been read (normally a backslash) final int c = in.read(); switch (c) { case 'r': return CR; case 'n': return LF; case 't': return TAB; case 'b': return BACKSPACE; case 'f': return FF...
int readEscape() throws IOException { // the escape char has just been read (normally a backslash) final int c = in.read(); switch (c) { case 'r': return CR; case 'n': return LF; case 't': return TAB; case 'b': return BACKSPACE; case 'f': return FF...
src/main/java/org/apache/commons/csv/Lexer.java
Unescape handling needs rethinking
The current escape parsing converts <esc><char> to plain <char> if the <char> is not one of the special characters to be escaped. This can affect unicode escapes if the <esc> character is backslash. One way round this is to specifically check for <char> == 'u', but it seems wrong to only do this for 'u'. Another soluti...
87
114
Csv-4
public Map<String, Integer> getHeaderMap() { return new LinkedHashMap<String, Integer>(this.headerMap); }
public Map<String, Integer> getHeaderMap() { return this.headerMap == null ? null : new LinkedHashMap<String, Integer>(this.headerMap); }
src/main/java/org/apache/commons/csv/CSVParser.java
CSVParser: getHeaderMap throws NPE
title nearly says it all Given a CSVParser parser, the following line throws an NPE: Map<String, Integer> header = parser.getHeaderMap(); Stacktrace: Caused by: java.lang.NullPointerException at java.util.HashMap.<init>(HashMap.java:318) at java.util.LinkedHashMap.<init>(LinkedHashMap.java:212) at org.apache.comm...
287
289
Csv-5
public void println() throws IOException { final String recordSeparator = format.getRecordSeparator(); out.append(recordSeparator); newRecord = true; }
public void println() throws IOException { final String recordSeparator = format.getRecordSeparator(); if (recordSeparator != null) { out.append(recordSeparator); } newRecord = true; }
src/main/java/org/apache/commons/csv/CSVPrinter.java
CSVFormat.format allways append null
When I now call CSVFormat.newFormat(';').withSkipHeaderRecord(true).withHeader("H1","H2").format("A","B") I get the output A;Bnull The expected output would be A;B
323
327
Csv-6
<M extends Map<String, String>> M putIn(final M map) { for (final Entry<String, Integer> entry : mapping.entrySet()) { final int col = entry.getValue().intValue(); map.put(entry.getKey(), values[col]); } return map; }
<M extends Map<String, String>> M putIn(final M map) { for (final Entry<String, Integer> entry : mapping.entrySet()) { final int col = entry.getValue().intValue(); if (col < values.length) { map.put(entry.getKey(), values[col]); } } return map; }
src/main/java/org/apache/commons/csv/CSVRecord.java
CSVRecord.toMap() fails if row length shorter than header length
Similar to CSV-96, if .toMap() is called on a record that has fewer fields than we have header columns we'll get an ArrayOutOfBoundsException. @Test public void testToMapWhenHeaderTooLong() throws Exception { final CSVParser parser = new CSVParser("a,b", CSVFormat.newBuilder().withHeader("A", "B", "C").build()); ...
179
185
Csv-7
private Map<String, Integer> initializeHeader() throws IOException { Map<String, Integer> hdrMap = null; final String[] formatHeader = this.format.getHeader(); if (formatHeader != null) { hdrMap = new LinkedHashMap<String, Integer>(); String[] header = null; ...
private Map<String, Integer> initializeHeader() throws IOException { Map<String, Integer> hdrMap = null; final String[] formatHeader = this.format.getHeader(); if (formatHeader != null) { hdrMap = new LinkedHashMap<String, Integer>(); String[] header = null; ...
src/main/java/org/apache/commons/csv/CSVParser.java
HeaderMap is inconsistent when it is parsed from an input with duplicate columns names
Given a parser format for csv files with a header line: {code} CSVFormat myFormat = CSVFormat.RFC4180.withDelimiter(",").withQuoteChar('"').withQuotePolicy(Quote.MINIMAL) .withIgnoreSurroundingSpaces(true).withHeader().withSkipHeaderRecord(true); {code} And given a file with duplicate header names: Col1,Col2,Col...
348
376
Csv-9
<M extends Map<String, String>> M putIn(final M map) { for (final Entry<String, Integer> entry : mapping.entrySet()) { final int col = entry.getValue().intValue(); if (col < values.length) { map.put(entry.getKey(), values[col]); } } return map; }
<M extends Map<String, String>> M putIn(final M map) { if (mapping == null) { return map; } for (final Entry<String, Integer> entry : mapping.entrySet()) { final int col = entry.getValue().intValue(); if (col < values.length) { map.put(entry.getKey(), values[col]); ...
src/main/java/org/apache/commons/csv/CSVRecord.java
CSVRecord.toMap() throws NPE on formats with no headers.
The method toMap() on CSVRecord throws a NullPointerExcpetion when called on records derived using a format with no headers. The method documentation states a null map should be returned instead.
179
187
Gson-11
public Number read(JsonReader in) throws IOException { JsonToken jsonToken = in.peek(); switch (jsonToken) { case NULL: in.nextNull(); return null; case NUMBER: return new LazilyParsedNumber(in.nextString()); default: throw new JsonSyntaxException("Expecting number, got: " + jsonToken); } }
public Number read(JsonReader in) throws IOException { JsonToken jsonToken = in.peek(); switch (jsonToken) { case NULL: in.nextNull(); return null; case NUMBER: case STRING: return new LazilyParsedNumber(in.nextString()); default: throw new JsonSyntaxException("Expecting number, got: " + jso...
gson/src/main/java/com/google/gson/internal/bind/TypeAdapters.java
Allow deserialization of a Number represented as a String
This works: gson.fromJson("\"15\"", int.class) This doesn't: gson.fromJson("\"15\"", Number.class) This PR makes it so the second case works too.
364
375
Gson-12
@Override public void skipValue() throws IOException { if (peek() == JsonToken.NAME) { nextName(); pathNames[stackSize - 2] = "null"; } else { popStack(); pathNames[stackSize - 1] = "null"; } pathIndices[stackSize - 1]++; }
@Override public void skipValue() throws IOException { if (peek() == JsonToken.NAME) { nextName(); pathNames[stackSize - 2] = "null"; } else { popStack(); if (stackSize > 0) { pathNames[stackSize - 1] = "null"; } } if (stackSize > 0) { pathIndices[stackSize - 1]++; } }
gson/src/main/java/com/google/gson/internal/bind/JsonTreeReader.java
Bug when skipping a value while using the JsonTreeReader
When using a JsonReader to read a JSON object, skipValue() skips the structure successfully. @Test public void testSkipValue_JsonReader() throws IOException { try (JsonReader in = new JsonReader(new StringReader("{}"))) { in.skipValue(); } } But when using a JsonTreeReader to read a JSON object, skipValue() thr...
256
265
Gson-15
public JsonWriter value(double value) throws IOException { writeDeferredName(); if (Double.isNaN(value) || Double.isInfinite(value)) { throw new IllegalArgumentException("Numeric values must be finite, but was " + value); } beforeValue(); out.append(Double.toString(value)); return this; }
public JsonWriter value(double value) throws IOException { writeDeferredName(); if (!lenient && (Double.isNaN(value) || Double.isInfinite(value))) { throw new IllegalArgumentException("Numeric values must be finite, but was " + value); } beforeValue(); out.append(Double.toString(value)); return this; }
gson/src/main/java/com/google/gson/stream/JsonWriter.java
JsonWriter#value(java.lang.Number) can be lenient, but JsonWriter#value(double) can't,
In lenient mode, JsonWriter#value(java.lang.Number) can write pseudo-numeric values like NaN, Infinity, -Infinity: if (!lenient && (string.equals("-Infinity") || string.equals("Infinity") || string.equals("NaN"))) { throw new IllegalArgumentException("Numeric values must be finite, but was " + value);...
493
501
Gson-17
public Date read(JsonReader in) throws IOException { if (in.peek() != JsonToken.STRING) { throw new JsonParseException("The date should be a string value"); } Date date = deserializeToDate(in.nextString()); if (dateType == Date.class) { return date; } else if (dateType == Timestamp.class) { return...
public Date read(JsonReader in) throws IOException { if (in.peek() == JsonToken.NULL) { in.nextNull(); return null; } Date date = deserializeToDate(in.nextString()); if (dateType == Date.class) { return date; } else if (dateType == Timestamp.class) { return new Timestamp(date.getTime()); } e...
gson/src/main/java/com/google/gson/DefaultDateTypeAdapter.java
Fixed DefaultDateTypeAdapter nullability issue and JSON primitives contract
Regression in: b8f616c - Migrate DefaultDateTypeAdapter to streaming adapter (#1070) Bug reports: #1096 - 2.8.1 can't serialize and deserialize date null (2.8.0 works fine) #1098 - Gson 2.8.1 DefaultDateTypeAdapter is not null safe. #1095 - serialize date sometimes TreeTypeAdapter, sometimes DefaultDateTypeAdapter?
98
113
Gson-18
static Type getSupertype(Type context, Class<?> contextRawType, Class<?> supertype) { // wildcards are useless for resolving supertypes. As the upper bound has the same raw type, use it instead checkArgument(supertype.isAssignableFrom(contextRawType)); return resolve(context, contextRawType, $Gson$Types.g...
static Type getSupertype(Type context, Class<?> contextRawType, Class<?> supertype) { if (context instanceof WildcardType) { // wildcards are useless for resolving supertypes. As the upper bound has the same raw type, use it instead context = ((WildcardType)context).getUpperBounds()[0]; } checkArgument(su...
gson/src/main/java/com/google/gson/internal/$Gson$Types.java
Gson deserializes wildcards to LinkedHashMap
This issue is a successor to #1101. Models: // ? extends causes the issue class BigClass { Map<String, ? extends List<SmallClass>> inBig; } class SmallClass { String inSmall; } Json: { "inBig": { "key": [ { "inSmall": "hello" } ] } } Gson call: SmallClass small = new Gson().fromJson(json, BigClass.cl...
277
282
Gson-6
static TypeAdapter<?> getTypeAdapter(ConstructorConstructor constructorConstructor, Gson gson, TypeToken<?> fieldType, JsonAdapter annotation) { Class<?> value = annotation.value(); TypeAdapter<?> typeAdapter; if (TypeAdapter.class.isAssignableFrom(value)) { Class<TypeAdapter<?>> typeAdapterClass = (Class...
static TypeAdapter<?> getTypeAdapter(ConstructorConstructor constructorConstructor, Gson gson, TypeToken<?> fieldType, JsonAdapter annotation) { Class<?> value = annotation.value(); TypeAdapter<?> typeAdapter; if (TypeAdapter.class.isAssignableFrom(value)) { Class<TypeAdapter<?>> typeAdapterClass = (Class...
gson/src/main/java/com/google/gson/internal/bind/JsonAdapterAnnotationTypeAdapterFactory.java
Fixed a regression in Gson 2.6 where Gson caused NPE if the TypeAdapt…
…erFactory.create() returned null.
51
69
JacksonCore-20
public void writeEmbeddedObject(Object object) throws IOException { // 01-Sep-2016, tatu: As per [core#318], handle small number of cases throw new JsonGenerationException("No native support for writing embedded objects", this); }
public void writeEmbeddedObject(Object object) throws IOException { // 01-Sep-2016, tatu: As per [core#318], handle small number of cases if (object == null) { writeNull(); return; } if (object instanceof byte[]) { writeBinary((byte[]) object); return; } throw new...
src/main/java/com/fasterxml/jackson/core/JsonGenerator.java
Add support for writing byte[] via JsonGenerator.writeEmbeddedObject()
(note: should be safe for patch, that is, 2.8.3) Default implementation of 2.8-added writeEmbeddedObject() throws exception (unsupported operation) for all values, since JSON does not have any native object types. This is different from handling of writeObject(), which tries to either delegate to ObjectCodec (if one re...
1,328
1,332
JacksonCore-23
public DefaultPrettyPrinter createInstance() { return new DefaultPrettyPrinter(this); }
public DefaultPrettyPrinter createInstance() { if (getClass() != DefaultPrettyPrinter.class) { // since 2.10 throw new IllegalStateException("Failed `createInstance()`: "+getClass().getName() +" does not override method; it has to"); } return new DefaultPrettyPrinter(this); }
src/main/java/com/fasterxml/jackson/core/util/DefaultPrettyPrinter.java
Make DefaultPrettyPrinter.createInstance() to fail for sub-classes
Pattern of "blueprint object" (that is, having an instance not used as-is, but that has factory method for creating actual instance) is used by Jackson in couple of places; often for things that implement Instantiatable. But one problem is that unless method is left abstract, sub-classing can be problematic -- if sub-c...
254
256
JacksonCore-25
private String _handleOddName2(int startPtr, int hash, int[] codes) throws IOException { _textBuffer.resetWithShared(_inputBuffer, startPtr, (_inputPtr - startPtr)); char[] outBuf = _textBuffer.getCurrentSegment(); int outPtr = _textBuffer.getCurrentSegmentSize(); final int maxCode = codes.length; ...
private String _handleOddName2(int startPtr, int hash, int[] codes) throws IOException { _textBuffer.resetWithShared(_inputBuffer, startPtr, (_inputPtr - startPtr)); char[] outBuf = _textBuffer.getCurrentSegment(); int outPtr = _textBuffer.getCurrentSegmentSize(); final int maxCode = codes.length; ...
src/main/java/com/fasterxml/jackson/core/json/ReaderBasedJsonParser.java
Fix ArrayIndexOutofBoundsException found by LGTM.com
First of all, thank you for reporting this. But would it be possible to write a test that shows how this actually works? It would be great to have a regression test, to guard against this happening in future.
1,948
1,990
JacksonCore-26
public void feedInput(byte[] buf, int start, int end) throws IOException { // Must not have remaining input if (_inputPtr < _inputEnd) { _reportError("Still have %d undecoded bytes, should not call 'feedInput'", _inputEnd - _inputPtr); } if (end < start) { _reportError("Input end (%d) ma...
public void feedInput(byte[] buf, int start, int end) throws IOException { // Must not have remaining input if (_inputPtr < _inputEnd) { _reportError("Still have %d undecoded bytes, should not call 'feedInput'", _inputEnd - _inputPtr); } if (end < start) { _reportError("Input end (%d) ma...
src/main/java/com/fasterxml/jackson/core/json/async/NonBlockingJsonParser.java
Non-blocking parser reports incorrect locations when fed with non-zero offset
When feeding a non-blocking parser, the input array offset leaks into the offsets reported by getCurrentLocation() and getTokenLocation(). For example, feeding with an offset of 7 yields tokens whose reported locations are 7 greater than they should be. Likewise the current location reported by the parser is 7 greater ...
88
112
JacksonCore-3
public UTF8StreamJsonParser(IOContext ctxt, int features, InputStream in, ObjectCodec codec, BytesToNameCanonicalizer sym, byte[] inputBuffer, int start, int end, boolean bufferRecyclable) { super(ctxt, features); _inputStream = in; _objectCodec = codec; _symbols = sym; _inpu...
public UTF8StreamJsonParser(IOContext ctxt, int features, InputStream in, ObjectCodec codec, BytesToNameCanonicalizer sym, byte[] inputBuffer, int start, int end, boolean bufferRecyclable) { super(ctxt, features); _inputStream = in; _objectCodec = codec; _symbols = sym; _inpu...
src/main/java/com/fasterxml/jackson/core/json/UTF8StreamJsonParser.java
_currInputRowStart isn't initialized in UTF8StreamJsonParser() constructor. The column position will be wrong.
The UTF8StreamJson Parser constructor allows to specify the start position. But it doesn't set the "_currInputRowStart" as the same value. It is still 0. So when raise the exception, the column calculation (ParserBase.getCurrentLocation() )will be wrong. int col = _inputPtr - _currInputRowStart + 1; // 1-based public ...
113
127
JacksonCore-4
public char[] expandCurrentSegment() { final char[] curr = _currentSegment; // Let's grow by 50% by default final int len = curr.length; // but above intended maximum, slow to increase by 25% int newLen = (len == MAX_SEGMENT_LEN) ? (MAX_SEGMENT_LEN+1) : Math.min(MAX_SEGMENT_LEN, len + (len >> 1)); ...
public char[] expandCurrentSegment() { final char[] curr = _currentSegment; // Let's grow by 50% by default final int len = curr.length; int newLen = len + (len >> 1); // but above intended maximum, slow to increase by 25% if (newLen > MAX_SEGMENT_LEN) { newLen = len + (len >> 2); } ...
src/main/java/com/fasterxml/jackson/core/util/TextBuffer.java
What is the maximum key length allowed?
I noticed that even in Jackson 2.4, if a JSON key is longer than 262144 bytes, ArrayIndexOutOfBoundsException is thrown from TextBuffer. Below is the stack trace: java.lang.ArrayIndexOutOfBoundsException at java.lang.System.arraycopy(Native Method) at com.fasterxml.jackson.core.util.TextBuffer.expandCurrentSegm...
580
588
JacksonCore-5
private final static int _parseIndex(String str) { final int len = str.length(); // [Issue#133]: beware of super long indexes; assume we never // have arrays over 2 billion entries so ints are fine. if (len == 0 || len > 10) { return -1; } for (int i = 0; i < len; ++i) { char c =...
private final static int _parseIndex(String str) { final int len = str.length(); // [Issue#133]: beware of super long indexes; assume we never // have arrays over 2 billion entries so ints are fine. if (len == 0 || len > 10) { return -1; } for (int i = 0; i < len; ++i) { char c =...
src/main/java/com/fasterxml/jackson/core/JsonPointer.java
An exception is thrown for a valid JsonPointer expression
Json-Patch project leader has noted me that there is a bug on JsonPointer implementation and I have decided to investigate. Basically if you do something like JsonPointer.compile("/1e0"); it throws a NumberFormatExpcetion which is not true. This is because this piece of code: private final static int _parseInt(String s...
185
205
JacksonCore-6
private final static int _parseIndex(String str) { final int len = str.length(); // [core#133]: beware of super long indexes; assume we never // have arrays over 2 billion entries so ints are fine. if (len == 0 || len > 10) { return -1; } // [core#176]: no leading zeroes allowed for ...
private final static int _parseIndex(String str) { final int len = str.length(); // [core#133]: beware of super long indexes; assume we never // have arrays over 2 billion entries so ints are fine. if (len == 0 || len > 10) { return -1; } // [core#176]: no leading zeroes allowed char...
src/main/java/com/fasterxml/jackson/core/JsonPointer.java
JsonPointer should not consider "00" to be valid index
Although 00 can be parsed as 0 in some cases, it is not a valid JSON number; and is also not legal numeric index for JSON Pointer. As such, JsonPointer class should ensure it can only match property name "00" and not array index.
185
206
JacksonCore-7
public int writeValue() { // Most likely, object: if (_type == TYPE_OBJECT) { _gotName = false; ++_index; return STATUS_OK_AFTER_COLON; } // Ok, array? if (_type == TYPE_ARRAY) { int ix = _index; ++_index; return (ix < 0) ? STATUS_OK_AS_IS : STATUS_OK...
public int writeValue() { // Most likely, object: if (_type == TYPE_OBJECT) { if (!_gotName) { return STATUS_EXPECT_NAME; } _gotName = false; ++_index; return STATUS_OK_AFTER_COLON; } // Ok, array? if (_type == TYPE_ARRAY) { int ix = _inde...
src/main/java/com/fasterxml/jackson/core/json/JsonWriteContext.java
Add a check so JsonGenerator.writeString() won't work if writeFieldName() expected.
Looks like calling writeString() (and perhaps other scalar write methods) results in writing invalid output, instead of throwing an exception. It should instead fail; in future we may want to consider allowing this as an alias, but at any rate it should not produce invalid output.
166
185
JacksonCore-8
public char[] getTextBuffer() { // Are we just using shared input buffer? if (_inputStart >= 0) return _inputBuffer; if (_resultArray != null) return _resultArray; if (_resultString != null) { return (_resultArray = _resultString.toCharArray()); } // Nope; but does it fit in just one se...
public char[] getTextBuffer() { // Are we just using shared input buffer? if (_inputStart >= 0) return _inputBuffer; if (_resultArray != null) return _resultArray; if (_resultString != null) { return (_resultArray = _resultString.toCharArray()); } // Nope; but does it fit in just one se...
src/main/java/com/fasterxml/jackson/core/util/TextBuffer.java
Inconsistent TextBuffer#getTextBuffer behavior
Hi, I'm using 2.4.2. While I'm working on CBORParser, I noticed that CBORParser#getTextCharacters() returns sometimes null sometimes [] (empty array) when it's parsing empty string "". While debugging, I noticed that TextBuffer#getTextBuffer behaves inconsistently. TextBuffer buffer = new TextBuffer(new BufferRecycler(...
298
310
JacksonDatabind-100
public byte[] getBinaryValue(Base64Variant b64variant) throws IOException, JsonParseException { // Multiple possibilities... JsonNode n = currentNode(); if (n != null) { // [databind#2096]: although `binaryValue()` works for real binary node // and embedded "POJO" node, coercion from Tex...
public byte[] getBinaryValue(Base64Variant b64variant) throws IOException, JsonParseException { // Multiple possibilities... JsonNode n = currentNode(); if (n != null) { // [databind#2096]: although `binaryValue()` works for real binary node // and embedded "POJO" node, coercion from Tex...
src/main/java/com/fasterxml/jackson/databind/node/TreeTraversingParser.java
TreeTraversingParser does not take base64 variant into account
This affects at least 2.6.4 to current versions. In TreeTraversingParser#getBinaryValue, a Base64Variant is accepted but ignored. The call to n.binaryValue(), when n is a TextNode, then uses the default Base64 variant instead of what's specified. It seems the correct behavior would be to call TextNode#getBinaryValue in...
355
376
JacksonDatabind-105
public static JsonDeserializer<?> find(Class<?> rawType, String clsName) { if (_classNames.contains(clsName)) { JsonDeserializer<?> d = FromStringDeserializer.findDeserializer(rawType); if (d != null) { return d; } if (rawType == UUID.class) { ...
public static JsonDeserializer<?> find(Class<?> rawType, String clsName) { if (_classNames.contains(clsName)) { JsonDeserializer<?> d = FromStringDeserializer.findDeserializer(rawType); if (d != null) { return d; } if (rawType == UUID.class) { ...
src/main/java/com/fasterxml/jackson/databind/deser/std/JdkDeserializers.java
Illegal reflective access operation warning when using `java.lang.Void` as value type
I'm using Jackson (**2.9.7**) through Spring's RestTemplate: ```java ResponseEntity<Void> response = getRestTemplate().exchange( requestUrl, HttpMethod.PATCH, new HttpEntity<>(dto, authHeaders), Void.class ); ``` When [`Void`](https://docs.oracle.com/javase/7/docs/api/java/lang/Void.html) is used t...
28
50
JacksonDatabind-107
protected final JsonDeserializer<Object> _findDeserializer(DeserializationContext ctxt, String typeId) throws IOException { JsonDeserializer<Object> deser = _deserializers.get(typeId); if (deser == null) { /* As per [databind#305], need to provide contextual info. But for * backwards co...
protected final JsonDeserializer<Object> _findDeserializer(DeserializationContext ctxt, String typeId) throws IOException { JsonDeserializer<Object> deser = _deserializers.get(typeId); if (deser == null) { /* As per [databind#305], need to provide contextual info. But for * backwards co...
src/main/java/com/fasterxml/jackson/databind/jsontype/impl/TypeDeserializerBase.java
DeserializationProblemHandler.handleUnknownTypeId() returning Void.class, enableDefaultTyping causing NPE
Returning Void.class from com.fasterxml.jackson.databind.deser.HandleUnknowTypeIdTest.testDeserializationWithDeserializationProblemHandler().new DeserializationProblemHandler() {...}.handleUnknownTypeId(DeserializationContext, JavaType, String, TypeIdResolver, String) is causing a NPE in jackson 2.9. I'll provide a pul...
146
199
JacksonDatabind-108
@SuppressWarnings("unchecked") @Override public <T extends TreeNode> T readTree(JsonParser p) throws IOException { return (T) _bindAsTree(p); }
@SuppressWarnings("unchecked") @Override public <T extends TreeNode> T readTree(JsonParser p) throws IOException { return (T) _bindAsTreeOrNull(p); }
src/main/java/com/fasterxml/jackson/databind/ObjectReader.java
Change of behavior (2.8 -> 2.9) with `ObjectMapper.readTree(input)` with no content
So, it looks like `readTree()` methods in `ObjectMapper`, `ObjectReader` that take input OTHER than `JsonParser`, and are given "empty input" (only white-space available before end), will * Return `NullNode` (Jackson 2.x up to and including 2.8) * Return `null` (Jackson 2.9) Latter behavior is what `readTree(Jso...
1,166
1,170
JacksonDatabind-11
protected JavaType _fromVariable(TypeVariable<?> type, TypeBindings context) { final String name = type.getName(); // 19-Mar-2015: Without context, all we can check are bounds. if (context == null) { // And to prevent infinite loops, now need this: return _unknownType(); } else { ...
protected JavaType _fromVariable(TypeVariable<?> type, TypeBindings context) { final String name = type.getName(); // 19-Mar-2015: Without context, all we can check are bounds. if (context == null) { // And to prevent infinite loops, now need this: context = new TypeBindings(this, (Class<?>)...
src/main/java/com/fasterxml/jackson/databind/type/TypeFactory.java
Problem resolving locally declared generic type
(reported by Hal H) Case like: class Something { public <T extends Ruleform> T getEntity() public <T extends Ruleform> void setEntity(T entity) } appears to fail on deserialization.
889
930
JacksonDatabind-112
public JsonDeserializer<?> createContextual(DeserializationContext ctxt, BeanProperty property) throws JsonMappingException { // May need to resolve types for delegate-based creators: JsonDeserializer<Object> delegate = null; if (_valueInstantiator != null) { // [databind#2324]: check both a...
public JsonDeserializer<?> createContextual(DeserializationContext ctxt, BeanProperty property) throws JsonMappingException { // May need to resolve types for delegate-based creators: JsonDeserializer<Object> delegate = null; if (_valueInstantiator != null) { // [databind#2324]: check both a...
src/main/java/com/fasterxml/jackson/databind/deser/std/StringCollectionDeserializer.java
StringCollectionDeserializer fails with custom collection
Seeing this with Jackson 2.9.8. We have a custom collection implementation, which is wired to use its "immutable" version for deserialization. The rationale is that we don't want accidental modifications to the data structures that come from the wire, so they all are forced to be immutable. After upgrade from 2.6.3 to ...
100
134
JacksonDatabind-12
public boolean isCachable() { /* As per [databind#735], existence of value or key deserializer (only passed * if annotated to use non-standard one) should also prevent caching. */ return (_valueTypeDeserializer == null) && (_ignorableProperties == null); }
public boolean isCachable() { /* As per [databind#735], existence of value or key deserializer (only passed * if annotated to use non-standard one) should also prevent caching. */ return (_valueDeserializer == null) && (_keyDeserializer == null) && (_valueTypeDeserializer == nu...
src/main/java/com/fasterxml/jackson/databind/deser/std/MapDeserializer.java
@JsonDeserialize on Map with contentUsing custom deserializer overwrites default behavior
I recently updated from version 2.3.3 to 2.5.1 and encountered a new issue with our custom deserializers. They either seemed to stop working or were active on the wrong fields. I could narrow it down to some change in version 2.4.4 (2.4.3 is still working for me) I wrote a test to show this behavior. It seems to appear...
299
305
JacksonDatabind-16
protected final boolean _add(Annotation ann) { if (_annotations == null) { _annotations = new HashMap<Class<? extends Annotation>,Annotation>(); } Annotation previous = _annotations.put(ann.annotationType(), ann); return (previous != null) && previous.equals(ann); }
protected final boolean _add(Annotation ann) { if (_annotations == null) { _annotations = new HashMap<Class<? extends Annotation>,Annotation>(); } Annotation previous = _annotations.put(ann.annotationType(), ann); return (previous == null) || !previous.equals(ann); }
src/main/java/com/fasterxml/jackson/databind/introspect/AnnotationMap.java
Annotation bundles ignored when added to Mixin
When updating from v 2.4.4 to 2.5.* it appears as though annotation bundles created with @JacksonAnnotationsInside are ignored when placed on a mixin. Moving the annotation bundel to the actual class seems to resolve the issue. Below is a simple test that attempts to rename a property. I have more complicated test c...
107
113
JacksonDatabind-19
private JavaType _mapType(Class<?> rawClass) { // 28-May-2015, tatu: Properties are special, as per [databind#810] JavaType[] typeParams = findTypeParameters(rawClass, Map.class); // ok to have no types ("raw") if (typeParams == null) { return MapType.construct(rawClass, _unknownType(), _unknown...
private JavaType _mapType(Class<?> rawClass) { // 28-May-2015, tatu: Properties are special, as per [databind#810] if (rawClass == Properties.class) { return MapType.construct(rawClass, CORE_TYPE_STRING, CORE_TYPE_STRING); } JavaType[] typeParams = findTypeParameters(rawClass, Map.class); //...
src/main/java/com/fasterxml/jackson/databind/type/TypeFactory.java
Force value coercion for java.util.Properties, so that values are Strings
Currently there is no custom handling for java.util.Properties, and although it is possible to use it (since it really is a Map under the hood), results are only good if values are already Strings. The problem here is that Properties is actually declared as Map<String,Object>, probably due to backwards-compatibility co...
1,018
1,031
JacksonDatabind-20
public JsonNode setAll(Map<String,? extends JsonNode> properties) { for (Map.Entry<String,? extends JsonNode> en : properties.entrySet()) { JsonNode n = en.getValue(); if (n == null) { n = nullNode(); } _children.put(en.getKey(), n); } ...
@JsonIgnore // work-around for [databind#815] public JsonNode setAll(Map<String,? extends JsonNode> properties) { for (Map.Entry<String,? extends JsonNode> en : properties.entrySet()) { JsonNode n = en.getValue(); if (n == null) { n = nullNode(); } ...
src/main/java/com/fasterxml/jackson/databind/node/ObjectNode.java
Presence of PropertyNamingStrategy Makes Deserialization Fail
I originally came across this issue using Dropwizard - https://github.com/dropwizard/dropwizard/issues/1095. But it looks like this is a Jackson issue. Here's the rerproducer: ``` java public class TestPropertyNamingStrategyIssue { public static class ClassWithObjectNodeField { public String id; public Obj...
324
334
JacksonDatabind-24
public BaseSettings withDateFormat(DateFormat df) { if (_dateFormat == df) { return this; } TimeZone tz = (df == null) ? _timeZone : df.getTimeZone(); return new BaseSettings(_classIntrospector, _annotationIntrospector, _visibilityChecker, _propertyNamingStrategy, _typeFactory, _type...
public BaseSettings withDateFormat(DateFormat df) { if (_dateFormat == df) { return this; } return new BaseSettings(_classIntrospector, _annotationIntrospector, _visibilityChecker, _propertyNamingStrategy, _typeFactory, _typeResolverBuilder, df, _handlerInstantiator, _locale, ...
src/main/java/com/fasterxml/jackson/databind/cfg/BaseSettings.java
Configuring an ObjectMapper's DateFormat changes time zone when serialising Joda DateTime
The serialisation of Joda DateTime instances behaves differently in 2.6.0 vs 2.5.4 when the ObjectMapper's had its DateFormat configured. The behaviour change is illustrated by the following code: public static void main(String[] args) throws JsonProcessingException { System.out.println(createObjectMapper() ...
230
238
JacksonDatabind-33
public PropertyName findNameForSerialization(Annotated a) { String name = null; JsonGetter jg = _findAnnotation(a, JsonGetter.class); if (jg != null) { name = jg.value(); } else { JsonProperty pann = _findAnnotation(a, JsonProperty.class); if (pann != null) { name = ...
public PropertyName findNameForSerialization(Annotated a) { String name = null; JsonGetter jg = _findAnnotation(a, JsonGetter.class); if (jg != null) { name = jg.value(); } else { JsonProperty pann = _findAnnotation(a, JsonProperty.class); if (pann != null) { name = ...
src/main/java/com/fasterxml/jackson/databind/introspect/JacksonAnnotationIntrospector.java
@JsonUnwrapped is not treated as assuming @JsonProperty("")
See discussion here but basically @JsonUnwrapped on a private field by itself does not cause that field to be serialized, currently, You need to add an explicit @JsonProperty. You shouldn't have to do that. (Following test fails currently, should pass, though you can make it pass by commenting out the line with @Jso...
731
755
JacksonDatabind-34
public void acceptJsonFormatVisitor(JsonFormatVisitorWrapper visitor, JavaType typeHint) throws JsonMappingException { if (_isInt) { visitIntFormat(visitor, typeHint, JsonParser.NumberType.BIG_INTEGER); } else { Class<?> h = handledType(); if (h == BigDecimal.class) { visitFl...
public void acceptJsonFormatVisitor(JsonFormatVisitorWrapper visitor, JavaType typeHint) throws JsonMappingException { if (_isInt) { visitIntFormat(visitor, typeHint, JsonParser.NumberType.BIG_INTEGER); } else { Class<?> h = handledType(); if (h == BigDecimal.class) { visitFl...
src/main/java/com/fasterxml/jackson/databind/ser/std/NumberSerializer.java
Regression in 2.7.0-rc2, for schema/introspection for BigDecimal
(found via Avro module, but surprisingly json schema module has not test to catch it) Looks like schema type for BigDecimal is not correctly produced, due to an error in refactoring (made to simplify introspection for simple serializers): it is seen as BigInteger (and for Avro, for example, results in long getting writ...
74
87
JacksonDatabind-35
private final Object _deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { // 02-Aug-2013, tatu: May need to use native type ids if (p.canReadTypeId()) { Object typeId = p.getTypeId(); if (typeId != null) { return _deserializeWithNativeTypeId(p, ctxt, typeId); ...
private final Object _deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { // 02-Aug-2013, tatu: May need to use native type ids if (p.canReadTypeId()) { Object typeId = p.getTypeId(); if (typeId != null) { return _deserializeWithNativeTypeId(p, ctxt, typeId); ...
src/main/java/com/fasterxml/jackson/databind/jsontype/impl/AsWrapperTypeDeserializer.java
Problem with Object Id and Type Id as Wrapper Object (regression in 2.5.1)
(note: originally from FasterXML/jackson-module-jaxb-annotations#51) Looks like fix for #669 caused a regression for the special use case of combining type and object ids, with wrapper-object type id inclusion. The problem started with 2.5.1.
79
120
JacksonDatabind-36
private final static DateFormat _cloneFormat(DateFormat df, String format, TimeZone tz, Locale loc, Boolean lenient) { if (!loc.equals(DEFAULT_LOCALE)) { df = new SimpleDateFormat(format, loc); df.setTimeZone((tz == null) ? DEFAULT_TIMEZONE : tz); } else { ...
private final static DateFormat _cloneFormat(DateFormat df, String format, TimeZone tz, Locale loc, Boolean lenient) { if (!loc.equals(DEFAULT_LOCALE)) { df = new SimpleDateFormat(format, loc); df.setTimeZone((tz == null) ? DEFAULT_TIMEZONE : tz); } else { ...
src/main/java/com/fasterxml/jackson/databind/util/StdDateFormat.java
Allow use of `StdDateFormat.setLenient()`
ObjectMapper uses the StdDateFormat for date serialization. Jackson date parsing is lenient by default, so 2015-01-32 gets parsed as 2015-02-01. Jackson’s StdDateParser is matching default behavior of DateParser. StdDateParser wasn’t really designed for extension to just enable strict date parsing. If it were, we ...
545
558
JacksonDatabind-39
public Object deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { // 29-Jan-2016, tatu: Simple skipping for all other tokens, but FIELD_NAME bit // special unfortunately p.skipChildren(); return null; }
public Object deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { // 29-Jan-2016, tatu: Simple skipping for all other tokens, but FIELD_NAME bit // special unfortunately if (p.hasToken(JsonToken.FIELD_NAME)) { while (true) { JsonToken t = p.nextToken(); ...
src/main/java/com/fasterxml/jackson/databind/deser/std/NullifyingDeserializer.java
Jackson not continue to parse after DeserializationFeature.FAIL_ON_INVALID_SUBTYPE error
After FAIL_ON_INVALID_SUBTYPE error, jackson should continue to parse, but seems jackson doesn't. The output: CallRecord [version=0.0, application=123, ] // doesn't read item2 which is valid CallRecord [version=0.0, application=123, ] CallRecord [version=0.0, ] // doesn't read application after invalid item. @JsonIncl...
31
37
JacksonDatabind-42
protected Object _deserializeFromEmptyString() throws IOException { // As per [databind#398], URI requires special handling if (_kind == STD_URI) { return URI.create(""); } // As per [databind#1123], Locale too return super._deserializeFromEmptyString(); }
protected Object _deserializeFromEmptyString() throws IOException { // As per [databind#398], URI requires special handling if (_kind == STD_URI) { return URI.create(""); } // As per [databind#1123], Locale too if (_kind == STD_LOCALE) { return Locale.ROOT; } return super._de...
src/main/java/com/fasterxml/jackson/databind/deser/std/FromStringDeserializer.java
Serializing and Deserializing Locale.ROOT
Serializing and Deserializing Locale objects seems to work just fine, until you try on the Root Locale. It writes it out as an empty string and when it reads it in, the value is null @Test public void testLocaleDeserialization() throws IOException { ObjectMapper objectMapper = new ObjectMapper(); Lo...
278
285
JacksonDatabind-43
@Override public Object deserializeSetAndReturn(JsonParser p, DeserializationContext ctxt, Object instance) throws IOException { Object id = _valueDeserializer.deserialize(p, ctxt); /* 02-Apr-2015, tatu: Actually, as per [databind#742], let it be; * missing or null id is needed f...
@Override public Object deserializeSetAndReturn(JsonParser p, DeserializationContext ctxt, Object instance) throws IOException { /* 02-Apr-2015, tatu: Actually, as per [databind#742], let it be; * missing or null id is needed for some cases, such as cases where id * will be gen...
src/main/java/com/fasterxml/jackson/databind/deser/impl/ObjectIdValueProperty.java
Problem with Object id handling, explicit `null` token
According to #742, it shouldn't throw an exception if the value of the property is null
74
96
JacksonDatabind-44
protected JavaType _narrow(Class<?> subclass) { if (_class == subclass) { return this; } // Should we check that there is a sub-class relationship? // 15-Jan-2016, tatu: Almost yes, but there are some complications with // placeholder values (`Void`, `NoClass`), so can not quite do yet. ...
protected JavaType _narrow(Class<?> subclass) { if (_class == subclass) { return this; } // Should we check that there is a sub-class relationship? // 15-Jan-2016, tatu: Almost yes, but there are some complications with // placeholder values (`Void`, `NoClass`), so can not quite do yet. ...
src/main/java/com/fasterxml/jackson/databind/type/SimpleType.java
Problem with polymorphic types, losing properties from base type(s)
(background, see: dropwizard/dropwizard#1449) Looks like sub-type resolution may be broken for one particular case: that of using defaultImpl. If so, appears like properties from super-types are not properly resolved; guessing this could be follow-up item for #1083 (even sooner than I thought...).
123
141
JacksonDatabind-45
public JsonSerializer<?> createContextual(SerializerProvider serializers, BeanProperty property) throws JsonMappingException { if (property != null) { JsonFormat.Value format = serializers.getAnnotationIntrospector().findFormat((Annotated)property.getMember()); if (format != null) { ...
public JsonSerializer<?> createContextual(SerializerProvider serializers, BeanProperty property) throws JsonMappingException { if (property != null) { JsonFormat.Value format = serializers.getAnnotationIntrospector().findFormat((Annotated)property.getMember()); if (format != null) { ...
src/main/java/com/fasterxml/jackson/databind/ser/std/DateTimeSerializerBase.java
Fix for #1154
Looks pretty good, but would it be possible to have a unit test that would fail before fix, pass after? Would be great to have something to guard against regression. I may want to change the logic a little bit, however; if shape is explicitly defined as NUMBER, textual representation should not be enabled even if Local...
50
81
JacksonDatabind-46
public StringBuilder getGenericSignature(StringBuilder sb) { _classSignature(_class, sb, false); sb.append('<'); sb = _referencedType.getGenericSignature(sb); sb.append(';'); return sb; }
public StringBuilder getGenericSignature(StringBuilder sb) { _classSignature(_class, sb, false); sb.append('<'); sb = _referencedType.getGenericSignature(sb); sb.append(">;"); return sb; }
src/main/java/com/fasterxml/jackson/databind/type/ReferenceType.java
Incorrect signature for generic type via `JavaType.getGenericSignature
(see FasterXML/jackson-modules-base#8 for background) It looks like generic signature generation is missing one closing > character to produce: ()Ljava/util/concurrent/atomic/AtomicReference<Ljava/lang/String;; instead of expected ()Ljava/util/concurrent/atomic/AtomicReference<Ljava/lang/String;>; that is, closing '>...
151
158
JacksonDatabind-49
public Object generateId(Object forPojo) { // 04-Jun-2016, tatu: As per [databind#1255], need to consider possibility of // id being generated for "alwaysAsId", but not being written as POJO; regardless, // need to use existing id if there is one: id = generator.generateId(forPojo); return...
public Object generateId(Object forPojo) { // 04-Jun-2016, tatu: As per [databind#1255], need to consider possibility of // id being generated for "alwaysAsId", but not being written as POJO; regardless, // need to use existing id if there is one: if (id == null) { id = generator.generateI...
src/main/java/com/fasterxml/jackson/databind/ser/impl/WritableObjectId.java
JsonIdentityInfo incorrectly serializing forward references
I wrote this small test program to demonstrate the issue: import com.fasterxml.jackson.annotation.JsonIdentityInfo; import com.fasterxml.jackson.annotation.JsonIdentityReference; import com.fasterxml.jackson.annotation.ObjectIdGenerators; import com.fasterxml.jackson.databind.ObjectMapper; public class ObjectIdTest { ...
46
52
JacksonDatabind-5
protected void _addMethodMixIns(Class<?> targetClass, AnnotatedMethodMap methods, Class<?> mixInCls, AnnotatedMethodMap mixIns) { List<Class<?>> parents = new ArrayList<Class<?>>(); parents.add(mixInCls); ClassUtil.findSuperTypes(mixInCls, targetClass, parents); for (Class<?> mixin : parents) { ...
protected void _addMethodMixIns(Class<?> targetClass, AnnotatedMethodMap methods, Class<?> mixInCls, AnnotatedMethodMap mixIns) { List<Class<?>> parents = new ArrayList<Class<?>>(); parents.add(mixInCls); ClassUtil.findSuperTypes(mixInCls, targetClass, parents); for (Class<?> mixin : parents) { ...
src/main/java/com/fasterxml/jackson/databind/introspect/AnnotatedClass.java
Mixin annotations lost when using a mixin class hierarchy with non-mixin interfaces
In summary, mixin annotations are lost when Jackson scans a parent mixin class with Json annotations followed by an interface implemented by the parent mixin class that does not have the same Json annotations. Jackson version: 2.4.0 Detail: I have the following class structure public interface Contact { String getC...
634
662
JacksonDatabind-51
protected final JsonDeserializer<Object> _findDeserializer(DeserializationContext ctxt, String typeId) throws IOException { JsonDeserializer<Object> deser = _deserializers.get(typeId); if (deser == null) { /* As per [Databind#305], need to provide contextual info. But for * backwards co...
protected final JsonDeserializer<Object> _findDeserializer(DeserializationContext ctxt, String typeId) throws IOException { JsonDeserializer<Object> deser = _deserializers.get(typeId); if (deser == null) { /* As per [Databind#305], need to provide contextual info. But for * backwards co...
src/main/java/com/fasterxml/jackson/databind/jsontype/impl/TypeDeserializerBase.java
Generic type returned from type id resolver seems to be ignored
https://github.com/benson-basis/jackson-custom-mess-tc Here's the situation, with Jackson 2.7.4. I have a TypeIdResolver that returns a JavaType for a generic type. However, something seems to be forgetting/erasing the generic, as it is failing to use the generic type param to understand the type of a field in the clas...
140
191
JacksonDatabind-55
@SuppressWarnings("unchecked") public static JsonSerializer<Object> getFallbackKeySerializer(SerializationConfig config, Class<?> rawKeyType) { if (rawKeyType != null) { // 29-Sep-2015, tatu: Odd case here, of `Enum`, which we may get for `EnumMap`; not sure // if t...
@SuppressWarnings("unchecked") public static JsonSerializer<Object> getFallbackKeySerializer(SerializationConfig config, Class<?> rawKeyType) { if (rawKeyType != null) { // 29-Sep-2015, tatu: Odd case here, of `Enum`, which we may get for `EnumMap`; not sure // if t...
src/main/java/com/fasterxml/jackson/databind/ser/std/StdKeySerializers.java
EnumMap keys not using enum's `@JsonProperty` values unlike Enum values
Based on these issues: https://github.com/FasterXML/jackson-databind/issues/677 https://github.com/FasterXML/jackson-databind/issues/1148 https://github.com/FasterXML/jackson-annotations/issues/96 I implemented @JsonProperty for my enum constants and they show up nicely when they are property values. But I also have a...
67
86
JacksonDatabind-57
public <T> MappingIterator<T> readValues(byte[] src, int offset, int length) throws IOException, JsonProcessingException { if (_dataFormatReaders != null) { return _detectBindAndReadValues(_dataFormatReaders.findFormat(src, offset, length), false); } return _bindAndReadValues(_considerFilter(_pa...
public <T> MappingIterator<T> readValues(byte[] src, int offset, int length) throws IOException, JsonProcessingException { if (_dataFormatReaders != null) { return _detectBindAndReadValues(_dataFormatReaders.findFormat(src, offset, length), false); } return _bindAndReadValues(_considerFilter(_pa...
src/main/java/com/fasterxml/jackson/databind/ObjectReader.java
ObjectReader.readValues() ignores offset and length when reading an array
ObjectReader.readValues ignores offset and length when reading an array. If _dataFormatReaders it will always use the full array: https://github.com/FasterXML/jackson-databind/blob/2.7/src/main/java/com/fasterxml/jackson/databind/ObjectReader.java#L1435
1,435
1,443
JacksonDatabind-63
public String getDescription() { if (_desc == null) { StringBuilder sb = new StringBuilder(); if (_from == null) { // can this ever occur? sb.append("UNKNOWN"); } else { Class<?> cls = (_from instanceof Class<?>) ? (Cla...
public String getDescription() { if (_desc == null) { StringBuilder sb = new StringBuilder(); if (_from == null) { // can this ever occur? sb.append("UNKNOWN"); } else { Class<?> cls = (_from instanceof Class<?>) ? (Cla...
src/main/java/com/fasterxml/jackson/databind/JsonMappingException.java
Reference-chain hints use incorrect class-name for inner classes
``` java import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.jupiter.api.Test; import java.io.IOException; import static com.google.co...
119
152
JacksonDatabind-7
public TokenBuffer deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException { copyCurrentStructure(jp); /* 28-Oct-2014, tatu: As per #592, need to support a special case of starting from * FIELD_NAME, which is taken to mean that we are missing START_OBJECT, but need * to as...
public TokenBuffer deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException { if (jp.getCurrentTokenId() != JsonToken.FIELD_NAME.id()) { copyCurrentStructure(jp); return this; } /* 28-Oct-2014, tatu: As per #592, need to support a special case of starting from * FIE...
src/main/java/com/fasterxml/jackson/databind/util/TokenBuffer.java
Possibly wrong TokenBuffer delegate deserialization using @JsonCreator
class Value { @JsonCreator public static Value from(TokenBuffer buffer) { ... } Given JSON string is { "a":1, "b":null }, it is expected that while deserializing using delegate buffer, current token will be start object {, and rest of the tokens will be available in buffer: [START_OBJECT, FIELD_NAME, VALUE_NUMBER_INT,...
403
411
JacksonDatabind-70
public void remove(SettableBeanProperty propToRm) { ArrayList<SettableBeanProperty> props = new ArrayList<SettableBeanProperty>(_size); String key = getPropertyName(propToRm); boolean found = false; for (int i = 1, end = _hashArea.length; i < end; i += 2) { SettableBeanProperty prop = (Settable...
public void remove(SettableBeanProperty propToRm) { ArrayList<SettableBeanProperty> props = new ArrayList<SettableBeanProperty>(_size); String key = getPropertyName(propToRm); boolean found = false; for (int i = 1, end = _hashArea.length; i < end; i += 2) { SettableBeanProperty prop = (Settable...
src/main/java/com/fasterxml/jackson/databind/deser/impl/BeanPropertyMap.java
ACCEPT_CASE_INSENSITIVE_PROPERTIES fails with @JsonUnwrapped
(note: moved from FasterXML/jackson-dataformat-csv#133) When trying to deserialize type like: public class Person { @JsonUnwrapped(prefix = "businessAddress.") public Address businessAddress; } public class Address { public String street; public String addon; public String zip = ""; public String town; ...
426
453
JacksonDatabind-71
public static StdKeyDeserializer forType(Class<?> raw) { int kind; // first common types: if (raw == String.class || raw == Object.class) { return StringKD.forType(raw); } else if (raw == UUID.class) { kind = TYPE_UUID; } else if (raw == Integer.class) { kind = TYPE_INT; ...
public static StdKeyDeserializer forType(Class<?> raw) { int kind; // first common types: if (raw == String.class || raw == Object.class || raw == CharSequence.class) { return StringKD.forType(raw); } else if (raw == UUID.class) { kind = TYPE_UUID; } else if (raw == Integer.class) {...
src/main/java/com/fasterxml/jackson/databind/deser/std/StdKeyDeserializer.java
Missing KeyDeserializer for CharSequence
Looks like use of nominal Map key type of CharSequence does not work yet (as of 2.7.8 / 2.8.6). This is something that is needed to work with certain frameworks, such as Avro's generated POJOs.
70
116
JacksonDatabind-74
protected Object _deserializeTypedUsingDefaultImpl(JsonParser p, DeserializationContext ctxt, TokenBuffer tb) throws IOException { // As per [JACKSON-614], may have default implementation to use JsonDeserializer<Object> deser = _findDefaultImplDeserializer(ctxt); if (deser != null) { if (tb ...
protected Object _deserializeTypedUsingDefaultImpl(JsonParser p, DeserializationContext ctxt, TokenBuffer tb) throws IOException { // As per [JACKSON-614], may have default implementation to use JsonDeserializer<Object> deser = _findDefaultImplDeserializer(ctxt); if (deser != null) { if (tb ...
src/main/java/com/fasterxml/jackson/databind/jsontype/impl/AsPropertyTypeDeserializer.java
AsPropertyTypeDeserializer ignores DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT
The AsPropertyTypeDeserializer implementation does not respect the DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT feature. When deserializing an empty String it throws DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT instead of creating a null Object.
134
160
JacksonDatabind-77
@Override public JsonDeserializer<Object> createBeanDeserializer(DeserializationContext ctxt, JavaType type, BeanDescription beanDesc) throws JsonMappingException { final DeserializationConfig config = ctxt.getConfig(); // We may also have custom overrides: JsonDeseri...
@Override public JsonDeserializer<Object> createBeanDeserializer(DeserializationContext ctxt, JavaType type, BeanDescription beanDesc) throws JsonMappingException { final DeserializationConfig config = ctxt.getConfig(); // We may also have custom overrides: JsonDeseri...
src/main/java/com/fasterxml/jackson/databind/deser/BeanDeserializerFactory.java
Jackson Deserializer security vulnerability via default typing (CVE-2017-7525)
I have send email to info@fasterxml.com
96
145
JacksonDatabind-78
@Override public JsonDeserializer<Object> createBeanDeserializer(DeserializationContext ctxt, JavaType type, BeanDescription beanDesc) throws JsonMappingException { final DeserializationConfig config = ctxt.getConfig(); // We may also have custom overrides: JsonDeseri...
@Override public JsonDeserializer<Object> createBeanDeserializer(DeserializationContext ctxt, JavaType type, BeanDescription beanDesc) throws JsonMappingException { final DeserializationConfig config = ctxt.getConfig(); // We may also have custom overrides: JsonDeseri...
src/main/java/com/fasterxml/jackson/databind/deser/BeanDeserializerFactory.java
Jackson Deserializer security vulnerability via default typing (CVE-2017-7525)
I have send email to info@fasterxml.com
110
158
JacksonDatabind-8
protected void verifyNonDup(AnnotatedWithParams newOne, int typeIndex, boolean explicit) { final int mask = (1 << typeIndex); _hasNonDefaultCreator = true; AnnotatedWithParams oldOne = _creators[typeIndex]; // already had an explicitly marked one? if (oldOne != null) { if ((_explicitCreator...
protected void verifyNonDup(AnnotatedWithParams newOne, int typeIndex, boolean explicit) { final int mask = (1 << typeIndex); _hasNonDefaultCreator = true; AnnotatedWithParams oldOne = _creators[typeIndex]; // already had an explicitly marked one? if (oldOne != null) { boolean verify; ...
src/main/java/com/fasterxml/jackson/databind/deser/impl/CreatorCollector.java
Problem with bogus conflict between single-arg-String vs CharSequence constructor
Although it is good idea to allow recognizing CharSequence as almost like an alias for String, this can cause problems for classes like StringBuilder that have separate constructors for both. This actually throws a bogus exception for 2.5.0, due to introduction of ability to recognize CharSequence.
276
308
JacksonDatabind-85
public JsonSerializer<?> createContextual(SerializerProvider serializers, BeanProperty property) throws JsonMappingException { if (property == null) { return this; } JsonFormat.Value format = findFormatOverrides(serializers, property, handledType()); if (f...
public JsonSerializer<?> createContextual(SerializerProvider serializers, BeanProperty property) throws JsonMappingException { if (property == null) { return this; } JsonFormat.Value format = findFormatOverrides(serializers, property, handledType()); if (f...
src/main/java/com/fasterxml/jackson/databind/ser/std/DateTimeSerializerBase.java
DateTimeSerializerBase ignores configured date format when creating contextual
DateTimeSerializerBase#createContextual creates a new serializer with StdDateFormat.DATE_FORMAT_STR_ISO8601 format instead of re-using the actual format that may have been specified on the configuration. See the following code: final String pattern = format.hasPattern() ? format.getP...
49
95
JacksonDatabind-88
protected JavaType _typeFromId(String id, DatabindContext ctxt) throws IOException { /* 30-Jan-2010, tatu: Most ids are basic class names; so let's first * check if any generics info is added; and only then ask factory * to do translation when necessary */ TypeFactory tf = ctxt.getTypeFacto...
protected JavaType _typeFromId(String id, DatabindContext ctxt) throws IOException { /* 30-Jan-2010, tatu: Most ids are basic class names; so let's first * check if any generics info is added; and only then ask factory * to do translation when necessary */ TypeFactory tf = ctxt.getTypeFacto...
src/main/java/com/fasterxml/jackson/databind/jsontype/impl/ClassNameIdResolver.java
Missing type checks when using polymorphic type ids
(report by Lukes Euler) JavaType supports limited amount of generic typing for textual representation, originally just to support typing needed for EnumMap (I think). Based on some reports, it appears that some of type compatibility checks are not performed in those cases; if so, they should be made since there is pote...
45
78