2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.netconf.nettyutil.handler;
10 import com.google.common.annotations.VisibleForTesting;
11 import com.google.common.base.Optional;
12 import io.netty.buffer.ByteBuf;
13 import io.netty.buffer.ByteBufOutputStream;
14 import io.netty.channel.ChannelHandlerContext;
15 import io.netty.handler.codec.MessageToByteEncoder;
16 import java.io.IOException;
17 import java.io.OutputStream;
18 import java.io.OutputStreamWriter;
19 import java.nio.charset.StandardCharsets;
20 import javax.xml.transform.TransformerException;
21 import javax.xml.transform.dom.DOMSource;
22 import javax.xml.transform.stream.StreamResult;
23 import org.opendaylight.netconf.api.NetconfMessage;
24 import org.slf4j.Logger;
25 import org.slf4j.LoggerFactory;
26 import org.w3c.dom.Comment;
28 public class NetconfMessageToXMLEncoder extends MessageToByteEncoder<NetconfMessage> {
29 private static final Logger LOG = LoggerFactory.getLogger(NetconfMessageToXMLEncoder.class);
31 private final Optional<String> clientId;
33 public NetconfMessageToXMLEncoder() {
34 this(Optional.<String>absent());
37 public NetconfMessageToXMLEncoder(final Optional<String> clientId) {
38 this.clientId = clientId;
43 public void encode(final ChannelHandlerContext ctx, final NetconfMessage msg, final ByteBuf out) throws IOException, TransformerException {
44 LOG.trace("Sent to encode : {}", msg);
46 if (clientId.isPresent()) {
47 Comment comment = msg.getDocument().createComment("clientId:" + clientId.get());
48 msg.getDocument().appendChild(comment);
51 try (OutputStream os = new ByteBufOutputStream(out)) {
52 // Wrap OutputStreamWriter with BufferedWriter as suggested in javadoc for OutputStreamWriter
54 // Using custom BufferedWriter that does not provide newLine method as performance improvement
55 // see javadoc for BufferedWriter
56 StreamResult result = new StreamResult(new BufferedWriter(new OutputStreamWriter(os, StandardCharsets.UTF_8)));
57 DOMSource source = new DOMSource(msg.getDocument());
58 ThreadLocalTransformers.getPrettyTransformer().transform(source, result);