Merge "Initial implementation of netconf monitoring module according to http://tools...
[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 org.opendaylight.controller.netconf.api.NetconfDeserializerException;
15 import org.opendaylight.controller.netconf.api.NetconfMessage;
16 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
17 import org.opendaylight.protocol.framework.DeserializerException;
18 import org.opendaylight.protocol.framework.DocumentedException;
19 import org.opendaylight.protocol.framework.ProtocolMessageFactory;
20 import org.opendaylight.protocol.util.ByteArray;
21 import org.slf4j.Logger;
22 import org.slf4j.LoggerFactory;
23 import org.w3c.dom.Comment;
24 import org.w3c.dom.Document;
25 import org.xml.sax.SAXException;
26
27 import java.io.ByteArrayInputStream;
28 import java.io.IOException;
29 import java.nio.ByteBuffer;
30 import java.util.Arrays;
31 import java.util.List;
32
33 /**
34  * NetconfMessageFactory for (de)serializing DOM documents.
35  */
36 public final class NetconfMessageFactory implements ProtocolMessageFactory<NetconfMessage> {
37
38     private static final Logger logger = LoggerFactory.getLogger(NetconfMessageFactory.class);
39
40     private final Optional<String> clientId;
41
42     public NetconfMessageFactory() {
43         clientId = Optional.absent();
44     }
45
46     public NetconfMessageFactory(Optional<String> clientId) {
47         this.clientId = clientId;
48     }
49
50     @Override
51     public NetconfMessage parse(byte[] bytes) throws DeserializerException, DocumentedException {
52         logMessage(bytes);
53
54         String additionalHeader = null;
55
56         if (startsWithAdditionalHeader(bytes)) {
57             // Auth information containing username, ip address... extracted for monitoring
58             int endOfAuthHeader = getAdditionalHeaderEndIndex(bytes);
59             if (endOfAuthHeader > -1) {
60                 byte[] additionalHeaderBytes = Arrays.copyOfRange(bytes, 0, endOfAuthHeader + 2);
61                 additionalHeader = additionalHeaderToString(additionalHeaderBytes);
62                 bytes = Arrays.copyOfRange(bytes, endOfAuthHeader + 2, bytes.length);
63             }
64         }
65         NetconfMessage message;
66         try {
67             Document doc = XmlUtil.readXmlToDocument(new ByteArrayInputStream(bytes));
68             message = new NetconfMessage(doc, additionalHeader);
69         } catch (final SAXException | IOException | IllegalStateException e) {
70             throw new NetconfDeserializerException("Could not parse message from " + new String(bytes), e);
71         }
72         return message;
73     }
74
75     private int getAdditionalHeaderEndIndex(byte[] bytes) {
76         for (String possibleEnd : Lists.newArrayList("]\n", "]\r\n")) {
77             int idx = ByteArray.findByteSequence(bytes, possibleEnd.getBytes(Charsets.UTF_8));
78
79             if (idx != -1) {
80                 return idx;
81             }
82         }
83
84         return -1;
85     }
86
87     private boolean startsWithAdditionalHeader(byte[] bytes) {
88         List<String> possibleStarts = Lists.newArrayList("[", "\r\n[", "\n[");
89         for (String possibleStart : possibleStarts) {
90             int i = 0;
91             for (byte b : possibleStart.getBytes(Charsets.UTF_8)) {
92                 if(bytes[i]!=b)
93                     break;
94
95                 return true;
96             }
97         }
98
99         return false;
100     };
101
102     private void logMessage(byte[] bytes) {
103         String s = Charsets.UTF_8.decode(ByteBuffer.wrap(bytes)).toString();
104         logger.debug("Parsing message \n{}", s);
105     }
106
107     private String additionalHeaderToString(byte[] bytes) {
108         return Charsets.UTF_8.decode(ByteBuffer.wrap(bytes)).toString();
109     }
110
111     @Override
112     public byte[] put(NetconfMessage netconfMessage) {
113         if (clientId.isPresent()) {
114             Comment comment = netconfMessage.getDocument().createComment("clientId:" + clientId.get());
115             netconfMessage.getDocument().appendChild(comment);
116         }
117         final ByteBuffer msgBytes = Charsets.UTF_8.encode(xmlToString(netconfMessage.getDocument()));
118         String content = xmlToString(netconfMessage.getDocument());
119
120         logger.trace("Putting message \n{}", content);
121         byte[] b = new byte[msgBytes.limit()];
122         msgBytes.get(b);
123         return b;
124     }
125
126     private String xmlToString(Document doc) {
127         return XmlUtil.toString(doc, false);
128     }
129 }