Initial code drop of netconf protocol implementation
[controller.git] / opendaylight / netconf / netconf-util / src / main / java / org / opendaylight / controller / netconf / util / messages / NetconfMessageFactory.java
1 /*
2  * Copyright (c) 2013 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
9 package org.opendaylight.controller.netconf.util.messages;
10
11 import com.google.common.base.Charsets;
12 import com.google.common.base.Optional;
13 import com.google.common.collect.Lists;
14 import io.netty.buffer.Unpooled;
15 import io.netty.channel.ChannelHandler;
16 import io.netty.handler.codec.DelimiterBasedFrameDecoder;
17 import org.opendaylight.controller.netconf.api.NetconfDeserializerException;
18 import org.opendaylight.controller.netconf.api.NetconfMessage;
19 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
20 import org.opendaylight.protocol.framework.DeserializerException;
21 import org.opendaylight.protocol.framework.DocumentedException;
22 import org.opendaylight.protocol.framework.ProtocolMessageFactory;
23 import org.opendaylight.protocol.util.ByteArray;
24 import org.slf4j.Logger;
25 import org.slf4j.LoggerFactory;
26 import org.w3c.dom.Comment;
27 import org.w3c.dom.Document;
28 import org.xml.sax.SAXException;
29
30 import java.io.ByteArrayInputStream;
31 import java.io.IOException;
32 import java.nio.ByteBuffer;
33 import java.util.Arrays;
34 import java.util.List;
35
36 /**
37  * NetconfMessageFactory for (de)serializing DOM documents.
38  */
39 public final class NetconfMessageFactory implements ProtocolMessageFactory<NetconfMessage> {
40
41     private static final Logger logger = LoggerFactory.getLogger(NetconfMessageFactory.class);
42
43     public static final byte[] endOfMessage = "]]>]]>".getBytes(Charsets.UTF_8);
44
45     public static final byte[] endOfChunk = "\n##\n".getBytes(Charsets.UTF_8);
46
47     private static final int MAX_CHUNK_SIZE = 1024; // Bytes
48
49     private FramingMechanism framing = FramingMechanism.EOM;
50
51     private final Optional<String> clientId;
52
53     public NetconfMessageFactory() {
54         clientId = Optional.absent();
55     }
56
57     public NetconfMessageFactory(Optional<String> clientId) {
58         this.clientId = clientId;
59     }
60
61     public static ChannelHandler getDelimiterFrameDecoder() {
62         return new DelimiterBasedFrameDecoder(Integer.MAX_VALUE, Unpooled.copiedBuffer(endOfMessage));
63     }
64
65     @Override
66     public List<NetconfMessage> parse(byte[] bytes) throws DeserializerException, DocumentedException {
67         String s = Charsets.UTF_8.decode(ByteBuffer.wrap(bytes)).toString();
68         logger.debug("Parsing message \n{}", s);
69         if (bytes[0] == '[') {
70             // yuma sends auth information in the first line. Ignore until ]\n
71             // is found.
72             int endOfAuthHeader = ByteArray.findByteSequence(bytes, new byte[] { ']', '\n' });
73             if (endOfAuthHeader > -1) {
74                 bytes = Arrays.copyOfRange(bytes, endOfAuthHeader + 2, bytes.length);
75             }
76         }
77         List<NetconfMessage> messages = Lists.newArrayList();
78         try {
79             Document doc = XmlUtil.readXmlToDocument(new ByteArrayInputStream(bytes));
80             messages.add(new NetconfMessage(doc));
81         } catch (final SAXException | IOException | IllegalStateException e) {
82             throw new NetconfDeserializerException("Could not parse message from " + new String(bytes), e);
83         }
84         return messages;
85     }
86
87     @Override
88     public byte[] put(NetconfMessage netconfMessage) {
89         if (clientId.isPresent()) {
90             Comment comment = netconfMessage.getDocument().createComment("clientId:" + clientId.get());
91             netconfMessage.getDocument().appendChild(comment);
92         }
93         byte[] bytes = (this.framing == FramingMechanism.EOM) ? this.putEOM(netconfMessage) : this
94                 .putChunked(netconfMessage);
95         String content = xmlToString(netconfMessage.getDocument());
96
97         logger.trace("Putting message \n{}", content);
98         return bytes;
99     }
100
101     private byte[] putEOM(NetconfMessage msg) {
102         // create byte buffer from the String XML
103         // all Netconf messages are encoded using UTF-8
104         final ByteBuffer msgBytes = Charsets.UTF_8.encode(xmlToString(msg.getDocument()));
105         final ByteBuffer result = ByteBuffer.allocate(msgBytes.limit() + endOfMessage.length);
106         result.put(msgBytes);
107         // put end of message
108         result.put(endOfMessage);
109         return result.array();
110     }
111
112     private byte[] putChunked(NetconfMessage msg) {
113         final ByteBuffer msgBytes = Charsets.UTF_8.encode(xmlToString(msg.getDocument()));
114         final NetconfMessageHeader h = new NetconfMessageHeader();
115         if (msgBytes.limit() > MAX_CHUNK_SIZE)
116             logger.warn("Netconf message too long, should be split.");
117         h.setLength(msgBytes.limit());
118         final byte[] headerBytes = h.toBytes();
119         final ByteBuffer result = ByteBuffer.allocate(headerBytes.length + msgBytes.limit() + endOfChunk.length);
120         result.put(headerBytes);
121         result.put(msgBytes);
122         result.put(endOfChunk);
123         return result.array();
124     }
125
126     private String xmlToString(Document doc) {
127         return XmlUtil.toString(doc, false);
128     }
129
130     /**
131      * For Hello message the framing is always EOM, but the framing mechanism
132      * may change.
133      *
134      * @param fm
135      *            new framing mechanism
136      */
137     public void setFramingMechanism(final FramingMechanism fm) {
138         logger.debug("Framing mechanism changed to {}", fm);
139         this.framing = fm;
140     }
141 }