BUG-2459: use thread-local cache of transformers 17/13317/13
authorRobert Varga <rovarga@cisco.com>
Tue, 2 Dec 2014 19:01:53 +0000 (20:01 +0100)
committerRobert Varga <nite@hq.sk>
Fri, 12 Dec 2014 12:41:34 +0000 (12:41 +0000)
As it turns out, we can reuse transformers in the encode path. Do
precisely that, keeping them in thread-local variables. This is safe in
context of Netty, as we are invoked only from the netty threadpool. This
has the benefit of reusing the transformers across all sessions
associated with the threadpool.

Change-Id: If57933f68a9c9196b649baea17353fd2bd472e09
Signed-off-by: Robert Varga <rovarga@cisco.com>
opendaylight/netconf/netconf-netty-util/src/main/java/org/opendaylight/controller/netconf/nettyutil/handler/NetconfMessageToEXIEncoder.java
opendaylight/netconf/netconf-netty-util/src/main/java/org/opendaylight/controller/netconf/nettyutil/handler/NetconfMessageToXMLEncoder.java
opendaylight/netconf/netconf-netty-util/src/main/java/org/opendaylight/controller/netconf/nettyutil/handler/ThreadLocalTransformers.java [new file with mode: 0644]

index 55dcd9d..f1e72ed 100644 (file)
@@ -14,11 +14,9 @@ import io.netty.channel.ChannelHandlerContext;
 import io.netty.handler.codec.MessageToByteEncoder;
 import java.io.IOException;
 import java.io.OutputStream;
-import javax.xml.transform.Transformer;
 import javax.xml.transform.TransformerException;
 import javax.xml.transform.dom.DOMSource;
 import javax.xml.transform.sax.SAXResult;
-import javax.xml.transform.sax.SAXTransformerFactory;
 import org.opendaylight.controller.netconf.api.NetconfMessage;
 import org.openexi.proc.common.EXIOptionsException;
 import org.openexi.sax.Transmogrifier;
@@ -26,10 +24,7 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 public final class NetconfMessageToEXIEncoder extends MessageToByteEncoder<NetconfMessage> {
-
     private static final Logger LOG = LoggerFactory.getLogger(NetconfMessageToEXIEncoder.class);
-
-    private static final SAXTransformerFactory saxTransformerFactory = (SAXTransformerFactory)SAXTransformerFactory.newInstance();
     private final NetconfEXICodec codec;
 
     public NetconfMessageToEXIEncoder(final NetconfEXICodec codec) {
@@ -44,8 +39,7 @@ public final class NetconfMessageToEXIEncoder extends MessageToByteEncoder<Netco
             final Transmogrifier transmogrifier = codec.getTransmogrifier();
             transmogrifier.setOutputStream(os);
 
-            final Transformer transformer = saxTransformerFactory.newTransformer();
-            transformer.transform(new DOMSource(msg.getDocument()), new SAXResult(transmogrifier.getSAXTransmogrifier()));
+            ThreadLocalTransformers.getDefaultTransformer().transform(new DOMSource(msg.getDocument()), new SAXResult(transmogrifier.getSAXTransmogrifier()));
         }
     }
 }
index d109e2d..99251b0 100644 (file)
@@ -17,10 +17,7 @@ import java.io.BufferedWriter;
 import java.io.IOException;
 import java.io.OutputStream;
 import java.io.OutputStreamWriter;
-import javax.xml.transform.OutputKeys;
-import javax.xml.transform.Transformer;
 import javax.xml.transform.TransformerException;
-import javax.xml.transform.TransformerFactory;
 import javax.xml.transform.dom.DOMSource;
 import javax.xml.transform.stream.StreamResult;
 import org.opendaylight.controller.netconf.api.NetconfMessage;
@@ -30,7 +27,6 @@ import org.w3c.dom.Comment;
 
 public class NetconfMessageToXMLEncoder extends MessageToByteEncoder<NetconfMessage> {
     private static final Logger LOG = LoggerFactory.getLogger(NetconfMessageToXMLEncoder.class);
-    private static final TransformerFactory FACTORY = TransformerFactory.newInstance();
 
     private final Optional<String> clientId;
 
@@ -38,13 +34,13 @@ public class NetconfMessageToXMLEncoder extends MessageToByteEncoder<NetconfMess
         this(Optional.<String>absent());
     }
 
-    public NetconfMessageToXMLEncoder(Optional<String> clientId) {
+    public NetconfMessageToXMLEncoder(final Optional<String> clientId) {
         this.clientId = clientId;
     }
 
     @Override
     @VisibleForTesting
-    public void encode(ChannelHandlerContext ctx, NetconfMessage msg, ByteBuf out) throws IOException, TransformerException {
+    public void encode(final ChannelHandlerContext ctx, final NetconfMessage msg, final ByteBuf out) throws IOException, TransformerException {
         LOG.trace("Sent to encode : {}", msg);
 
         if (clientId.isPresent()) {
@@ -53,14 +49,10 @@ public class NetconfMessageToXMLEncoder extends MessageToByteEncoder<NetconfMess
         }
 
         try (OutputStream os = new ByteBufOutputStream(out)) {
-            Transformer transformer = FACTORY.newTransformer();
-            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
-            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
-
             // Wrap OutputStreamWriter with BufferedWriter as suggested in javadoc for OutputStreamWriter
             StreamResult result = new StreamResult(new BufferedWriter(new OutputStreamWriter(os)));
             DOMSource source = new DOMSource(msg.getDocument());
-            transformer.transform(source, result);
+            ThreadLocalTransformers.getPrettyTransformer().transform(source, result);
         }
     }
 }
diff --git a/opendaylight/netconf/netconf-netty-util/src/main/java/org/opendaylight/controller/netconf/nettyutil/handler/ThreadLocalTransformers.java b/opendaylight/netconf/netconf-netty-util/src/main/java/org/opendaylight/controller/netconf/nettyutil/handler/ThreadLocalTransformers.java
new file mode 100644 (file)
index 0000000..a2039d6
--- /dev/null
@@ -0,0 +1,82 @@
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.netconf.nettyutil.handler;
+
+import javax.xml.transform.OutputKeys;
+import javax.xml.transform.Transformer;
+import javax.xml.transform.TransformerConfigurationException;
+import javax.xml.transform.TransformerFactory;
+import javax.xml.transform.TransformerFactoryConfigurationError;
+
+/**
+ * Utility class for cached thread-local transformers. This class exists mostly for use by handlers.
+ */
+final class ThreadLocalTransformers {
+    private static final TransformerFactory FACTORY = TransformerFactory.newInstance();
+
+    private static final ThreadLocal<Transformer> DEFAULT_TRANSFORMER = new ThreadLocal<Transformer>() {
+        @Override
+        protected Transformer initialValue() {
+            try {
+                return FACTORY.newTransformer();
+            } catch (TransformerConfigurationException | TransformerFactoryConfigurationError e) {
+                throw new IllegalStateException("Unexpected error while instantiating a Transformer", e);
+            }
+        };
+
+        @Override
+        public void set(final Transformer value) {
+            throw new UnsupportedOperationException();
+        };
+    };
+
+    private static final ThreadLocal<Transformer> PRETTY_TRANSFORMER = new ThreadLocal<Transformer>() {
+        @Override
+        protected Transformer initialValue() {
+            final Transformer ret;
+
+            try {
+                ret = FACTORY.newTransformer();
+            } catch (TransformerConfigurationException | TransformerFactoryConfigurationError e) {
+                throw new IllegalStateException("Unexpected error while instantiating a Transformer", e);
+            }
+
+            ret.setOutputProperty(OutputKeys.INDENT, "yes");
+            ret.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
+            return ret;
+        };
+
+        @Override
+        public void set(final Transformer value) {
+            throw new UnsupportedOperationException();
+        };
+    };
+
+    private ThreadLocalTransformers() {
+        throw new UnsupportedOperationException("Utility class");
+    }
+
+    /**
+     * Get the transformer with default configuration.
+     *
+     * @return A transformer with default configuration based on the default implementation.
+     */
+    public static Transformer getDefaultTransformer() {
+        return DEFAULT_TRANSFORMER.get();
+    }
+
+    /**
+     * Get the transformer with default configuration, but with automatic indentation
+     * and the XML declaration removed.
+     *
+     * @return A transformer with human-friendly configuration.
+     */
+    public static Transformer getPrettyTransformer() {
+        return PRETTY_TRANSFORMER.get();
+    }
+}