Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
Expand Down Expand Up @@ -33,7 +35,7 @@ public void serialize(Object object, OutputStream outputStream) throws IOExcepti

// Our xml util xml to json
try {
jsonString = JsonXmlUtil.xmlToJson(xmlString);
jsonString = xmlToJson(xmlString);
} catch (Exception e) {
logger.error(e);
throw new SerializerException(e);
Expand All @@ -42,6 +44,63 @@ public void serialize(Object object, OutputStream outputStream) throws IOExcepti
outputStream.write(jsonString.getBytes());
}

/**
* A character reference to a character that XML 1.0 does not allow, such as U+FFFE or a C0
* control other than tab, LF or CR. XStream writes these for such characters in free text
* (code templates, scripts, descriptions), and the XML parser in JsonXmlUtil rejects them, which
* failed the whole response. See OpenIntegrationEngine/engine#566.
*/
private static final Pattern CHARACTER_REFERENCE = Pattern.compile("&#(?:[xX]([0-9a-fA-F]+)|([0-9]+));");

/**
* Converts the XML to JSON. Character references that XML 1.0 does not allow are swapped for a
* private-use placeholder that does not occur in this document, and turned back into JSON
* escapes afterwards, so the characters come through unchanged.
*/
static String xmlToJson(String xml) throws Exception {
char marker = unusedPrivateUseCharacter(xml);
StringBuilder protectedXml = new StringBuilder(xml.length());
Matcher matcher = CHARACTER_REFERENCE.matcher(xml);
boolean replaced = false;

while (matcher.find()) {
int codePoint = parseCodePoint(matcher);
String replacement = matcher.group();

if (codePoint >= 0 && codePoint <= 0xFFFF && !isXml10Char(codePoint)) {
replacement = marker + String.format("%04x", codePoint);
replaced = true;
}

matcher.appendReplacement(protectedXml, Matcher.quoteReplacement(replacement));
}
matcher.appendTail(protectedXml);

String json = JsonXmlUtil.xmlToJson(replaced ? protectedXml.toString() : xml);
return replaced ? json.replaceAll(Pattern.quote(String.valueOf(marker)) + "([0-9a-f]{4})", "\\\\u$1") : json;
}

private static int parseCodePoint(Matcher matcher) {
try {
return matcher.group(1) != null ? Integer.parseInt(matcher.group(1), 16) : Integer.parseInt(matcher.group(2));
} catch (NumberFormatException e) {
return -1;
}
}

private static boolean isXml10Char(int codePoint) {
return codePoint == 0x9 || codePoint == 0xA || codePoint == 0xD || (codePoint >= 0x20 && codePoint <= 0xD7FF) || (codePoint >= 0xE000 && codePoint <= 0xFFFD);
}

private static char unusedPrivateUseCharacter(String text) {
for (char candidate = ''; candidate <= ''; candidate++) {
if (text.indexOf(candidate) < 0) {
return candidate;
}
}
throw new IllegalStateException("No unused private-use character is available for the XML to JSON conversion");
}

/* Converts a source JSON string to XML then calls ObjectXMLSerializer.deserialize(...)
* JSON -> XML -> Object
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,25 @@
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonObject;
import javax.json.JsonReader;
import javax.json.JsonString;
import javax.json.JsonValue;

import org.junit.BeforeClass;
import org.junit.Test;

import com.mirth.connect.client.core.Version;
import com.mirth.connect.model.Channel;
import com.mirth.connect.model.InvalidChannel;
import com.mirth.connect.model.codetemplates.CodeTemplate;
import com.mirth.connect.model.codetemplates.CodeTemplateContextSet;
import com.mirth.connect.model.codetemplates.CodeTemplateProperties.CodeTemplateType;

public class ObjectJSONSerializerTest {

Expand Down Expand Up @@ -64,6 +72,56 @@ public void testSerializeChannel() throws IOException {
assertEquals(channelId, id);
}

/**
* Characters that XML 1.0 does not allow (U+FFFE, U+FFFF and C0 controls other than tab, LF
* and CR) must not stop JSON serialization, and must come through unchanged. See
* OpenIntegrationEngine/engine#566.
*/
@Test
public void testSerializeCodeTemplateWithXmlIllegalCharacters() throws IOException {
String code = "s.replace(/[￾￿]/g, \"\"); // \u0001 \u001F \u0008";
CodeTemplate codeTemplate = new CodeTemplate("illegal characters", CodeTemplateType.FUNCTION, CodeTemplateContextSet.getGlobalContextSet(), code);

JsonValue json = serializeToJson(codeTemplate);

assertTrue("the code template's code is in the JSON unchanged", containsString(json, code));
}

/** The placeholder used for those characters must not collide with text already present. */
@Test
public void testSerializeKeepsPrivateUseCharactersAlongsideXmlIllegalCharacters() throws IOException {
String description = "fffe; then ￾ then ";
Channel channel = new Channel();
channel.setId(GOOD_OLD_CHANNEL_ID);
channel.setDescription(description);

JsonValue json = serializeToJson(channel);

assertEquals(description, ((JsonObject) json).getJsonObject("channel").getString("description"));
}

private static JsonValue serializeToJson(Object object) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectJSONSerializer.getInstance().serialize(object, baos);

try (JsonReader jsonReader = Json.createReader(new InputStreamReader(new ByteArrayInputStream(baos.toByteArray()), StandardCharsets.UTF_8))) {
return jsonReader.read();
}
}

private static boolean containsString(JsonValue value, String expected) {
switch (value.getValueType()) {
case STRING:
return expected.equals(((JsonString) value).getString());
case OBJECT:
return ((JsonObject) value).values().stream().anyMatch(child -> containsString(child, expected));
case ARRAY:
return ((JsonArray) value).stream().anyMatch(child -> containsString(child, expected));
default:
return false;
}
}

private static final String GOOD_OLD_CHANNEL_ID = "e084f86d-7743-4df8-a6eb-91d1cdf2ab0f";
// @formatter:off
private static final String GOOD_OLD_CHANNEL =
Expand Down
Loading