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.controller.netconf.nettyutil.handler;
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.Transformer;
18 import javax.xml.transform.TransformerException;
19 import javax.xml.transform.dom.DOMSource;
20 import javax.xml.transform.sax.SAXResult;
21 import org.opendaylight.controller.netconf.api.NetconfMessage;
22 import org.openexi.proc.common.EXIOptionsException;
23 import org.openexi.sax.Transmogrifier;
24 import org.openexi.sax.TransmogrifierException;
25 import org.slf4j.Logger;
26 import org.slf4j.LoggerFactory;
27 import org.xml.sax.ContentHandler;
29 public final class NetconfMessageToEXIEncoder extends MessageToByteEncoder<NetconfMessage> {
30 private static final Logger LOG = LoggerFactory.getLogger(NetconfMessageToEXIEncoder.class);
32 * This class is not marked as shared, so it can be attached to only a single channel,
33 * which means that {@link #encode(ChannelHandlerContext, NetconfMessage, ByteBuf)}
34 * cannot be invoked concurrently. Hence we can reuse the transmogrifier.
36 private final Transmogrifier transmogrifier;
38 private NetconfMessageToEXIEncoder(final Transmogrifier transmogrifier) {
39 this.transmogrifier = Preconditions.checkNotNull(transmogrifier);
42 public static NetconfMessageToEXIEncoder create(final NetconfEXICodec codec) throws EXIOptionsException, TransmogrifierException {
43 return new NetconfMessageToEXIEncoder(codec.getTransmogrifier());
47 protected void encode(final ChannelHandlerContext ctx, final NetconfMessage msg, final ByteBuf out) throws EXIOptionsException, IOException, TransformerException, TransmogrifierException {
48 LOG.trace("Sent to encode : {}", msg);
50 try (final OutputStream os = new ByteBufOutputStream(out)) {
51 transmogrifier.setOutputStream(os);
52 final ContentHandler handler = transmogrifier.getSAXTransmogrifier();
53 final Transformer transformer = ThreadLocalTransformers.getDefaultTransformer();
54 transformer.transform(new DOMSource(msg.getDocument()), new SAXResult(handler));
56 // Make sure we do not retain any reference to state by removing
57 // the output stream reference and resetting internal state.
58 transmogrifier.setOutputStream(null);
59 transmogrifier.getSAXTransmogrifier();