Use java.util.Optional
[netconf.git] / netconf / netconf-netty-util / src / main / java / org / opendaylight / netconf / nettyutil / handler / NetconfMessageToXMLEncoder.java
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.netconf.nettyutil.handler;
9
10 import com.google.common.annotations.VisibleForTesting;
11 import io.netty.buffer.ByteBuf;
12 import io.netty.buffer.ByteBufOutputStream;
13 import io.netty.channel.ChannelHandlerContext;
14 import io.netty.handler.codec.MessageToByteEncoder;
15 import java.io.IOException;
16 import java.io.OutputStream;
17 import java.io.OutputStreamWriter;
18 import java.nio.charset.StandardCharsets;
19 import java.util.Optional;
20 import javax.xml.transform.TransformerException;
21 import javax.xml.transform.dom.DOMSource;
22 import javax.xml.transform.stream.StreamResult;
23 import org.eclipse.jdt.annotation.Nullable;
24 import org.opendaylight.netconf.api.NetconfMessage;
25 import org.slf4j.Logger;
26 import org.slf4j.LoggerFactory;
27 import org.w3c.dom.Comment;
28
29 public class NetconfMessageToXMLEncoder extends MessageToByteEncoder<NetconfMessage> {
30     private static final Logger LOG = LoggerFactory.getLogger(NetconfMessageToXMLEncoder.class);
31
32     private final @Nullable String clientId;
33
34     public NetconfMessageToXMLEncoder() {
35         this(Optional.empty());
36     }
37
38     public NetconfMessageToXMLEncoder(final Optional<String> clientId) {
39         this.clientId = clientId.orElse(null);
40     }
41
42     @Override
43     @VisibleForTesting
44     public void encode(final ChannelHandlerContext ctx, final NetconfMessage msg, final ByteBuf out)
45             throws IOException, TransformerException {
46         LOG.trace("Sent to encode : {}", msg);
47
48         if (clientId != null) {
49             Comment comment = msg.getDocument().createComment("clientId:" + clientId);
50             msg.getDocument().appendChild(comment);
51         }
52
53         try (OutputStream os = new ByteBufOutputStream(out)) {
54             // Wrap OutputStreamWriter with BufferedWriter as suggested in javadoc for OutputStreamWriter
55
56             // Using custom BufferedWriter that does not provide newLine method as performance improvement
57             // see javadoc for BufferedWriter
58             StreamResult result =
59                     new StreamResult(new BufferedWriter(new OutputStreamWriter(os, StandardCharsets.UTF_8)));
60             DOMSource source = new DOMSource(msg.getDocument());
61             ThreadLocalTransformers.getPrettyTransformer().transform(source, result);
62         }
63     }
64 }