Avoid possible NPE when deserializing a BuildException

This commit is contained in:
Guillaume Nodet
2020-10-29 18:03:43 +01:00
parent fb0ab1ffac
commit 5b5eab4908
2 changed files with 28 additions and 0 deletions

View File

@@ -114,6 +114,9 @@ public abstract class Message {
static String readUTF(DataInputStream input) throws IOException {
byte[] byteBuf = BUF_TLS.get();
int len = input.readInt();
if (len == -1) {
return null;
}
final char[] chars = new char[len];
int i = 0, cnt = 0, charIdx = 0;
while (charIdx < len) {
@@ -176,6 +179,10 @@ public abstract class Message {
static void writeUTF(DataOutputStream output, String s) throws IOException {
byte[] byteBuf = BUF_TLS.get();
if (s == null) {
output.writeInt(-1);
return;
}
final int length = s.length();
output.writeInt(length);
int strIdx = 0;

View File

@@ -23,6 +23,7 @@ import java.io.IOException;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class MessageTest {
@@ -48,4 +49,24 @@ public class MessageTest {
assertTrue(msg2 instanceof Message.BuildMessage);
assertEquals(stringToWrite.toString(), ((Message.BuildMessage) msg2).getMessage());
}
@Test
void buildExceptionSerialization() throws Exception {
Message msg = new Message.BuildException(new NullPointerException());
assertNull(((Message.BuildException) msg).getMessage());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (DataOutputStream daos = new DataOutputStream(baos)) {
msg.write(daos);
}
Message msg2;
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
try (DataInputStream dis = new DataInputStream(bais)) {
msg2 = Message.read(dis);
}
assertTrue(msg2 instanceof Message.BuildException);
assertNull(((Message.BuildException) msg2).getMessage());
}
}