Merge "BUG-1766: escape outbound strings"
authorTony Tkacik <ttkacik@cisco.com>
Thu, 11 Sep 2014 09:06:19 +0000 (09:06 +0000)
committerGerrit Code Review <gerrit@opendaylight.org>
Thu, 11 Sep 2014 09:06:19 +0000 (09:06 +0000)
yang/yang-data-codec-gson/src/main/java/org/opendaylight/yangtools/yang/data/codec/gson/JSONNormalizedNodeStreamWriter.java

index 058ad5b78e8cb95729dbf90025ed4b3cdcd87e45..643e9de9ad041f9b2c4c3c02bf6e3d3317061295 100644 (file)
@@ -7,6 +7,7 @@
  */
 package org.opendaylight.yangtools.yang.data.codec.gson;
 
+import com.google.common.base.CharMatcher;
 import com.google.common.base.Preconditions;
 import com.google.common.base.Strings;
 import com.google.gson.stream.JsonWriter;
@@ -41,6 +42,11 @@ public class JSONNormalizedNodeStreamWriter implements NormalizedNodeStreamWrite
      */
     private static final boolean DEFAULT_EMIT_EMPTY_CONTAINERS = true;
 
+    /**
+     * Matcher used to check if a string needs to be escaped.
+     */
+    private static final CharMatcher QUOTES_OR_BACKSLASH = CharMatcher.anyOf("\\\"");
+
     private final SchemaTracker tracker;
     private final JSONCodecFactory codecs;
     private final Writer writer;
@@ -222,7 +228,24 @@ public class JSONNormalizedNodeStreamWriter implements NormalizedNodeStreamWrite
     private void writeValue(final String str, final boolean needQuotes) throws IOException {
         if (needQuotes) {
             writer.append('"');
-            writer.append(str);
+
+            final int needEscape = QUOTES_OR_BACKSLASH.countIn(str);
+            if (needEscape != 0) {
+                final char[] escaped = new char[str.length() + needEscape];
+                int offset = 0;
+
+                for (int i = 0; i < str.length(); i++) {
+                    final char c = str.charAt(i);
+                    if (QUOTES_OR_BACKSLASH.matches(c)) {
+                        escaped[offset++] = '\\';
+                    }
+                    escaped[offset++] = c;
+                }
+                writer.write(escaped);
+            } else {
+                writer.append(str);
+            }
+
             writer.append('"');
         } else {
             writer.append(str);