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