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