package fr.insee.rmes.utils;

import java.io.IOException;
import java.io.OutputStream;
import java.io.Writer;

import org.codehaus.stax2.io.EscapingWriterFactory;

public class CustomXmlEscapingWriterFactory implements EscapingWriterFactory {
public Writer createEscapingWriterFor(final Writer out, String enc) {
    return new Writer(){
        @Override
        public void write(char[] cbuf, int off, int len) throws IOException {
            String val = "";
            for (int i = off; i < len; i++) {
                val += cbuf[i];
            }
            String escapedStr = escapeHtml(val); //convert special characters excluding xml tags
            out.write(escapedStr);
        }

        @Override
        public void flush() throws IOException {
            out.flush();
        }

        @Override
        public void close() throws IOException {
            out.close();
        }
      };
    }

	private String escapeHtml(String s) {
		 return s.replace("&", "&amp;")
				 .replace(">", "&gt;")
				 .replace("<", "&lt;")
				 .replace("\"", "&quot;");
				// .replace("'", "&apos;");
	}

    public Writer createEscapingWriterFor(OutputStream out, String enc) {
        throw new IllegalArgumentException("not supported");
    }
}
@@ -236,16 +236,20 @@
 ctory %7B%0A
+%09%0A%09%0A
 public W
@@ -423,32 +423,118 @@
 s IOException %7B%0A
+        %09//WARN : the cbuf contains only part of the string = can't validate xml here%0A
             Stri
@@ -670,16 +670,26 @@
 edStr = 
+encodeXml(
 escapeHt
@@ -699,48 +699,33 @@
 val)
+)
 ; //
-convert special characters excluding
+encode manually some
  xml
@@ -997,16 +997,17 @@
 %0A    %7D%0A%0A
+%0A
 %09private
@@ -1161,38 +1161,308 @@
 );%0A%09
-%09%09%09// .replace(%22'%22, %22&apos;%22);
+%7D%0A%09%0A%09private String encodeXml(String s) %7B%0A%09%09 return s.replaceAll(%22&lt;(%5Ba-zA-Z%5D+)&gt;%22, %22%3C$1%3E%22) //xml open tag%0A%09%09%09%09 .replaceAll(%22&lt;/(%5Ba-zA-Z%5D+)&gt;%22, %22%3C/$1%3E%22) //xml close tag%0A%09%09%09%09 .replaceAll(%22&lt;(%5Ba-zA-Z%5D+)/&gt;%22, %22%3C$1/%3E%22) //br%0A%09%09%09%09 .replaceAll(%22&lt;(%5Ba-zA-Z%5D+) /&gt;%22, %22%3C$1 /%3E%22); //br with space
 %0A%09%7D%0A

Change encoding of xml to encode all except xml tags