Merge "Refactor Additional header for netconf hello message."
[controller.git] / opendaylight / netconf / netconf-util / src / main / java / org / opendaylight / controller / netconf / util / handler / NetconfHelloMessageToXMLEncoder.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 java.nio.ByteBuffer;
11
12 import org.opendaylight.controller.netconf.api.NetconfMessage;
13 import org.opendaylight.controller.netconf.util.messages.NetconfHelloMessage;
14 import org.opendaylight.controller.netconf.util.messages.NetconfHelloMessageAdditionalHeader;
15
16 import com.google.common.base.Charsets;
17 import com.google.common.base.Optional;
18 import com.google.common.base.Preconditions;
19
20 /**
21  * Customized NetconfMessageToXMLEncoder that serializes additional header with
22  * session metadata along with
23  * {@link org.opendaylight.controller.netconf.util.messages.NetconfHelloMessage}
24  * . Used by netconf clients to send information about the user, ip address,
25  * protocol etc.
26  * <p/>
27  * Hello message with header example:
28  * <p/>
29  *
30  * <pre>
31  * {@code
32  * [tomas;10.0.0.0/10000;tcp;1000;1000;;/home/tomas;;]
33  * <hello xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
34  * <capabilities>
35  * <capability>urn:ietf:params:netconf:base:1.0</capability>
36  * </capabilities>
37  * </hello>
38  * }
39  * </pre>
40  */
41 public final class NetconfHelloMessageToXMLEncoder extends NetconfMessageToXMLEncoder {
42
43     @Override
44     protected ByteBuffer encodeMessage(NetconfMessage msg) {
45         Preconditions.checkState(msg instanceof NetconfHelloMessage, "Netconf message of type %s expected, was %s",
46                 NetconfHelloMessage.class, msg.getClass());
47         Optional<NetconfHelloMessageAdditionalHeader> headerOptional = ((NetconfHelloMessage) msg)
48                 .getAdditionalHeader();
49
50         // If additional header present, serialize it along with netconf hello
51         // message
52         if (headerOptional.isPresent()) {
53             byte[] bytesFromHeader = headerOptional.get().toFormattedString().getBytes(Charsets.UTF_8);
54             byte[] bytesFromMessage = xmlToString(msg.getDocument()).getBytes(Charsets.UTF_8);
55
56             ByteBuffer byteBuffer = ByteBuffer.allocate(bytesFromHeader.length + bytesFromMessage.length)
57                     .put(bytesFromHeader).put(bytesFromMessage);
58             byteBuffer.flip();
59             return byteBuffer;
60         }
61
62         return super.encodeMessage(msg);
63     }
64 }