Skip to content

Commit 5455445

Browse files
committed
RawValue.toString ignores malformed bytes instead of throwing MessageTypeException
1 parent 3320e07 commit 5455445

File tree

2 files changed

+35
-1
lines changed

2 files changed

+35
-1
lines changed

src/main/java/org/msgpack/type/AbstractRawValue.java

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,12 @@
1818
package org.msgpack.type;
1919

2020
import java.util.Arrays;
21+
import java.nio.ByteBuffer;
22+
import java.nio.charset.Charset;
23+
import java.nio.charset.CharacterCodingException;
24+
import java.nio.charset.CharsetDecoder;
25+
import java.nio.charset.CodingErrorAction;
26+
import java.nio.charset.MalformedInputException;
2127

2228
abstract class AbstractRawValue extends AbstractValue implements RawValue {
2329
public ValueType getType() {
@@ -56,7 +62,24 @@ public String toString() {
5662
}
5763

5864
public StringBuilder toString(StringBuilder sb) {
59-
String s = getString();
65+
String s;
66+
if(getClass() == StringRawValueImpl.class) {
67+
// StringRawValueImpl.getString never throws exception
68+
s = getString();
69+
} else {
70+
// don't throw encoding error exception
71+
// ignore malformed bytes
72+
CharsetDecoder decoder = Charset.forName("UTF-8").newDecoder().
73+
onMalformedInput(CodingErrorAction.IGNORE).
74+
onUnmappableCharacter(CodingErrorAction.IGNORE);
75+
try {
76+
s = decoder.decode(ByteBuffer.wrap(getByteArray())).toString();
77+
} catch (CharacterCodingException ex) {
78+
// never comes here
79+
s = new String(getByteArray());
80+
}
81+
}
82+
6083
sb.append("\"");
6184
for(int i=0; i < s.length(); i++) {
6285
char ch = s.charAt(i);
@@ -102,6 +125,7 @@ public StringBuilder toString(StringBuilder sb) {
102125
}
103126
}
104127
sb.append("\"");
128+
105129
return sb;
106130
}
107131

src/test/java/org/msgpack/unpacker/TestMalformedEncoding.java

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,5 +126,15 @@ public void testJSONBufferPackerWriteString() throws Exception {
126126
}
127127
}
128128
}
129+
130+
@Test
131+
public void testValueToString() throws Exception {
132+
for(byte[] malform : malforms) {
133+
RawValue r = ValueFactory.rawValue(malform);
134+
String str = r.toString();
135+
// malformed bytes will be ignored
136+
assertEquals("\"\"", str);
137+
}
138+
}
129139
}
130140

0 commit comments

Comments
 (0)