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 static org.junit.Assert.assertArrayEquals;
11 import static org.junit.Assert.assertEquals;
12 import static org.junit.Assert.assertFalse;
14 import io.netty.buffer.Unpooled;
15 import java.io.ByteArrayOutputStream;
16 import java.util.ArrayList;
17 import java.util.Arrays;
18 import javax.xml.transform.dom.DOMSource;
19 import javax.xml.transform.sax.SAXResult;
20 import org.junit.Before;
21 import org.junit.Test;
22 import org.opendaylight.netconf.api.messages.NetconfMessage;
23 import org.opendaylight.netconf.api.xml.XmlUtil;
24 import org.opendaylight.netconf.nettyutil.handler.exi.EXIParameters;
25 import org.xmlunit.builder.DiffBuilder;
27 public class NetconfEXIHandlersTest {
28 private final String msgAsString = "<netconf-message/>";
30 private NetconfMessageToEXIEncoder netconfMessageToEXIEncoder;
31 private NetconfEXIToMessageDecoder netconfEXIToMessageDecoder;
32 private NetconfMessage msg;
33 private byte[] msgAsExi;
36 public void setUp() throws Exception {
37 final var codec = NetconfEXICodec.forParameters(EXIParameters.empty());
38 netconfMessageToEXIEncoder = NetconfMessageToEXIEncoder.create(codec);
39 netconfEXIToMessageDecoder = NetconfEXIToMessageDecoder.create(codec);
41 msg = new NetconfMessage(XmlUtil.readXmlToDocument(msgAsString));
42 msgAsExi = msgToExi(msg, codec);
45 private static byte[] msgToExi(final NetconfMessage msg, final NetconfEXICodec codec) throws Exception {
46 final var bos = new ByteArrayOutputStream();
47 final var encoder = codec.getWriter();
48 encoder.setOutputStream(bos);
49 ThreadLocalTransformers.getDefaultTransformer().transform(new DOMSource(msg.getDocument()),
50 new SAXResult(encoder));
51 return bos.toByteArray();
55 public void testEncodeDecode() throws Exception {
56 final var buffer = Unpooled.buffer();
57 netconfMessageToEXIEncoder.encode(null, msg, buffer);
58 final int exiLength = msgAsExi.length;
59 // array from buffer is cca 256 n length, compare only subarray
60 assertArrayEquals(msgAsExi, Arrays.copyOfRange(buffer.array(), 0, exiLength));
62 // assert all other bytes in buffer be 0
63 for (int i = exiLength; i < buffer.array().length; i++) {
64 assertEquals((byte)0, buffer.array()[i]);
67 final var out = new ArrayList<>();
68 netconfEXIToMessageDecoder.decode(null, buffer, out);
70 final var diff = DiffBuilder.compare(msg.getDocument())
71 .withTest(((NetconfMessage) out.get(0)).getDocument())
74 assertFalse(diff.toString(), diff.hasDifferences());