2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
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
9 package org.opendaylight.controller.netconf.client;
11 import io.netty.channel.Channel;
12 import io.netty.util.Timer;
13 import io.netty.util.concurrent.Promise;
15 import java.io.IOException;
16 import java.io.InputStream;
18 import org.opendaylight.controller.netconf.api.NetconfMessage;
19 import org.opendaylight.controller.netconf.api.NetconfSessionPreferences;
20 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
21 import org.opendaylight.protocol.framework.SessionListenerFactory;
22 import org.opendaylight.protocol.framework.SessionNegotiator;
23 import org.opendaylight.protocol.framework.SessionNegotiatorFactory;
24 import org.xml.sax.SAXException;
26 import com.google.common.base.Optional;
27 import com.google.common.base.Preconditions;
29 public class NetconfClientSessionNegotiatorFactory implements SessionNegotiatorFactory<NetconfMessage, NetconfClientSession, NetconfClientSessionListener> {
31 private final Optional<String> additionalHeader;
32 private final long connectionTimeoutMillis;
33 private final Timer timer;
35 public NetconfClientSessionNegotiatorFactory(Timer timer, Optional<String> additionalHeader, long connectionTimeoutMillis) {
36 this.timer = Preconditions.checkNotNull(timer);
37 this.additionalHeader = additionalHeader;
38 this.connectionTimeoutMillis = connectionTimeoutMillis;
41 private static NetconfMessage loadHelloMessageTemplate() {
42 final String helloMessagePath = "/client_hello.xml";
43 try (InputStream is = NetconfClientSessionNegotiatorFactory.class.getResourceAsStream(helloMessagePath)) {
44 Preconditions.checkState(is != null, "Input stream from %s was null", helloMessagePath);
45 return new NetconfMessage(XmlUtil.readXmlToDocument(is));
46 } catch (SAXException | IOException e) {
47 throw new RuntimeException("Unable to load hello message", e);
52 public SessionNegotiator<NetconfClientSession> getSessionNegotiator(SessionListenerFactory<NetconfClientSessionListener> sessionListenerFactory, Channel channel,
53 Promise<NetconfClientSession> promise) {
54 // Hello message needs to be recreated every time
55 NetconfMessage helloMessage = loadHelloMessageTemplate();
56 if(this.additionalHeader.isPresent()) {
57 helloMessage = new NetconfMessage(helloMessage.getDocument(), additionalHeader.get());
59 NetconfSessionPreferences proposal = new NetconfSessionPreferences(helloMessage);
60 return new NetconfClientSessionNegotiator(proposal, promise, channel, timer,
61 sessionListenerFactory.getSessionListener(), connectionTimeoutMillis);