Merge "BUG 2509 : Removing all journal entries from a Followers in-memory journal...
[controller.git] / opendaylight / netconf / netconf-netty-util / src / main / java / org / opendaylight / controller / netconf / nettyutil / handler / NetconfMessageToEXIEncoder.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.controller.netconf.nettyutil.handler;
9
10 import com.google.common.base.Preconditions;
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 javax.xml.transform.TransformerException;
18 import javax.xml.transform.dom.DOMSource;
19 import javax.xml.transform.sax.SAXResult;
20 import org.opendaylight.controller.netconf.api.NetconfMessage;
21 import org.openexi.proc.common.EXIOptionsException;
22 import org.openexi.sax.Transmogrifier;
23 import org.openexi.sax.TransmogrifierException;
24 import org.slf4j.Logger;
25 import org.slf4j.LoggerFactory;
26
27 public final class NetconfMessageToEXIEncoder extends MessageToByteEncoder<NetconfMessage> {
28     private static final Logger LOG = LoggerFactory.getLogger(NetconfMessageToEXIEncoder.class);
29     private final NetconfEXICodec codec;
30
31     public NetconfMessageToEXIEncoder(final NetconfEXICodec codec) {
32         this.codec = Preconditions.checkNotNull(codec);
33     }
34
35     @Override
36     protected void encode(final ChannelHandlerContext ctx, final NetconfMessage msg, final ByteBuf out) throws EXIOptionsException, IOException, TransformerException, TransmogrifierException {
37         LOG.trace("Sent to encode : {}", msg);
38
39         try (final OutputStream os = new ByteBufOutputStream(out)) {
40             final Transmogrifier transmogrifier = codec.getTransmogrifier();
41             transmogrifier.setOutputStream(os);
42
43             ThreadLocalTransformers.getDefaultTransformer().transform(new DOMSource(msg.getDocument()), new SAXResult(transmogrifier.getSAXTransmogrifier()));
44         }
45     }
46 }