Merge "Fix warnings reported in toaster"
[controller.git] / opendaylight / netconf / netconf-util / src / main / java / org / opendaylight / controller / netconf / util / handler / NetconfXMLToMessageDecoder.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.util.handler;
9
10 import io.netty.buffer.ByteBuf;
11 import io.netty.buffer.ByteBufUtil;
12 import io.netty.channel.ChannelHandlerContext;
13 import io.netty.handler.codec.ByteToMessageDecoder;
14
15 import java.io.ByteArrayInputStream;
16 import java.io.IOException;
17 import java.nio.ByteBuffer;
18 import java.util.Arrays;
19 import java.util.List;
20
21 import org.opendaylight.controller.netconf.api.NetconfDeserializerException;
22 import org.opendaylight.controller.netconf.api.NetconfMessage;
23 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
24 import org.slf4j.Logger;
25 import org.slf4j.LoggerFactory;
26 import org.w3c.dom.Document;
27 import org.xml.sax.SAXException;
28
29 import com.google.common.annotations.VisibleForTesting;
30 import com.google.common.base.Charsets;
31 import com.google.common.collect.ImmutableList;
32
33 public final class NetconfXMLToMessageDecoder extends ByteToMessageDecoder {
34     private static final Logger LOG = LoggerFactory.getLogger(NetconfXMLToMessageDecoder.class);
35
36     // FIXME: this is funky way of creating arrays
37     private static final List<byte[]> POSSIBLE_ENDS = ImmutableList.of(
38             "]\n".getBytes(Charsets.UTF_8), "]\r\n".getBytes(Charsets.UTF_8));
39     private static final List<byte[]> POSSIBLE_STARTS = ImmutableList.of(
40             "[".getBytes(Charsets.UTF_8), "\r\n[".getBytes(Charsets.UTF_8), "\n[".getBytes(Charsets.UTF_8));
41
42     @Override
43     @VisibleForTesting
44     public void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
45         if (in.readableBytes() == 0) {
46             LOG.debug("No more content in incoming buffer.");
47             return;
48         }
49
50         in.markReaderIndex();
51         try {
52             LOG.trace("Received to decode: {}", ByteBufUtil.hexDump(in));
53             byte[] bytes = new byte[in.readableBytes()];
54             in.readBytes(bytes);
55
56             logMessage(bytes);
57
58             String additionalHeader = null;
59
60             if (startsWithAdditionalHeader(bytes)) {
61                 // Auth information containing username, ip address... extracted for monitoring
62                 int endOfAuthHeader = getAdditionalHeaderEndIndex(bytes);
63                 if (endOfAuthHeader > -1) {
64                     byte[] additionalHeaderBytes = Arrays.copyOfRange(bytes, 0, endOfAuthHeader + 2);
65                     additionalHeader = additionalHeaderToString(additionalHeaderBytes);
66                     bytes = Arrays.copyOfRange(bytes, endOfAuthHeader + 2, bytes.length);
67                 }
68             }
69             NetconfMessage message;
70             try {
71                 Document doc = XmlUtil.readXmlToDocument(new ByteArrayInputStream(bytes));
72                 message = new NetconfMessage(doc, additionalHeader);
73             } catch (final SAXException | IOException | IllegalStateException e) {
74                 throw new NetconfDeserializerException("Could not parse message from " + new String(bytes), e);
75             }
76
77             out.add(message);
78         } finally {
79             in.discardReadBytes();
80         }
81     }
82
83     private int getAdditionalHeaderEndIndex(byte[] bytes) {
84         for (byte[] possibleEnd : POSSIBLE_ENDS) {
85             int idx = findByteSequence(bytes, possibleEnd);
86
87             if (idx != -1) {
88                 return idx;
89             }
90         }
91
92         return -1;
93     }
94
95     private static int findByteSequence(final byte[] bytes, final byte[] sequence) {
96         if (bytes.length < sequence.length) {
97             throw new IllegalArgumentException("Sequence to be found is longer than the given byte array.");
98         }
99         if (bytes.length == sequence.length) {
100             if (Arrays.equals(bytes, sequence)) {
101                 return 0;
102             } else {
103                 return -1;
104             }
105         }
106         int j = 0;
107         for (int i = 0; i < bytes.length; i++) {
108             if (bytes[i] == sequence[j]) {
109                 j++;
110                 if (j == sequence.length) {
111                     return i - j + 1;
112                 }
113             } else {
114                 j = 0;
115             }
116         }
117         return -1;
118     }
119
120     private boolean startsWithAdditionalHeader(byte[] bytes) {
121         for (byte[] possibleStart : POSSIBLE_STARTS) {
122             int i = 0;
123             for (byte b : possibleStart) {
124                 if(bytes[i] != b)
125                     break;
126
127                 return true;
128             }
129         }
130
131         return false;
132     };
133
134     private void logMessage(byte[] bytes) {
135         String s = Charsets.UTF_8.decode(ByteBuffer.wrap(bytes)).toString();
136         LOG.debug("Parsing message \n{}", s);
137     }
138
139     private String additionalHeaderToString(byte[] bytes) {
140         return Charsets.UTF_8.decode(ByteBuffer.wrap(bytes)).toString();
141     }
142
143 }