Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright 2015 Open Networking Laboratory
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *     http://www.apache.org/licenses/LICENSE-2.0
   *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
 package org.onosproject.provider.netconf.device.impl;
 
 import static com.google.common.base.Preconditions.checkNotNull;
 import static org.onlab.util.Tools.delay;
 import static org.slf4j.LoggerFactory.getLogger;
 
 import java.util.List;
 
 
This is a logical representation of actual NETCONF device, carrying all the necessary information to connect and execute NETCONF operations.
 
 public class NetconfDevice {
     private final Logger log = getLogger(NetconfDevice.class);

    
The Device State is used to determine whether the device is active or inactive. This state infomation will help Device Creator to add or delete the device from the core.
 
     public static enum DeviceState {
         /* Used to specify Active state of the device */
         ACTIVE,
         /* Used to specify inactive state of the device */
         INACTIVE,
         /* Used to specify invalid state of the device */
         INVALID
     }
 
     private static final int DEFAULT_SSH_PORT = 22;
     private static final int DEFAULT_CON_TIMEOUT = 0;
     private static final String XML_CAPABILITY_KEY = "capability";
     private static final int EVENTINTERVAL = 2000;
     private static final int CONNECTION_CHECK_INTERVAL = 3;
     private static final String INPUT_HELLO_XML_MSG = new StringBuilder(
                                                                         "<?xml version=\"1.0\" encoding=\"UTF-8\"?>")
             .append("<hello xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">")
             .append("<capabilities><capability>urn:ietf:params:netconf:base:1.0</capability>")
             .append("</capabilities></hello>").toString();
 
     private String sshHost;
     private int sshPort = ;
     private int connectTimeout = ;
     private String username;
     private String password;
     private boolean reachable = false;
 
     private List<Stringcapabilities = new ArrayList<String>();
     private SSHConnection sshConnection = null;
 
     private DeviceState deviceState = .;
 
     protected NetconfDevice(String sshHostint sshPortString username,
                             String password) {
         this. = checkNotNull(username,
                                      "Netconf Username Cannot be null");
         this. = checkNotNull(sshHost"Netconf Device IP cannot be null");
         this. = checkNotNull(sshPort,
                                     "Netconf Device SSH port cannot be null");
         this. = password;
     }

    
This will try to connect to NETCONF device and find all the capabilities.

Throws:
java.lang.Exception if unable to connect to the device
 
     // FIXME: this should not be a generic Exception; perhaps wrap in some RuntimeException
     public void init() throws Exception {
        try {
            if ( == null) {
                 = new SSHConnection();
                .authenticateWithPassword();
            }
            // Send hello message to retrieve capabilities.
        } catch (IOException e) {
            .error("Fatal Error while creating connection to the device: "
                    + deviceInfo(), e);
            throw e;
        } catch (JNCException e) {
            .error("Failed to connect to the device: " + deviceInfo(), e);
            throw e;
        }
        hello();
    }
    private void hello() {
        SSHSession ssh = null;
        try {
            ssh = new SSHSession();
            String helloRequestXML = .trim();
            .debug("++++++++++++++++++++++++++++++++++Sending Hello: "
                    + .getGanymedConnection().getHostname()
                    + "++++++++++++++++++++++++++++++++++");
            printPrettyXML(helloRequestXML);
            ssh.print(helloRequestXML);
            // ssh.print(endCharSeq);
            ssh.flush();
            String xmlResponse = null;
            int i = ;
            while (!ssh.ready() && i > 0) {
                delay();
                i--;
            }
            if (ssh.ready()) {
                StringBuffer readOne = ssh.readOne();
                if (readOne == null) {
                    .error("The Hello Contains No Capabilites");
                    throw new JNCException(
                                           .,
                                           "server does not support NETCONF base capability: "
                                                   + .);
                } else {
                    xmlResponse = readOne.toString().trim();
                    .debug("++++++++++++++++++++++++++++++++++Reading Capabilities: "
                            + .getGanymedConnection()
                                    .getHostname()
                            + "++++++++++++++++++++++++++++++++++");
                    printPrettyXML(xmlResponse);
                    processCapabilities(xmlResponse);
                }
            }
             = true;
        } catch (IOException e) {
            .error("Fatal Error while sending Hello Message to the device: "
                    + deviceInfo(), e);
        } catch (JNCException e) {
            .error("Fatal Error while sending Hello Message to the device: "
                    + deviceInfo(), e);
        } finally {
            .debug("Closing the session after successful execution");
            ssh.close();
        }
    }
    private void processCapabilities(String xmlResponsethrows JNCException {
        if (xmlResponse.isEmpty()) {
            .error("The capability response cannot be empty");
            throw new JNCException(
                                   .,
                                   "server does not support NETCONF base capability: "
                                           + .);
        }
        try {
            Document doc = new SAXBuilder()
                    .build(new StringReader(xmlResponse));
            Element rootElement = doc.getRootElement();
            processCapabilities(rootElement);
        } catch (Exception e) {
            .error("ERROR while parsing the XML " + xmlResponse);
        }
    }
    private void processCapabilities(Element rootElement) {
        List<Elementchildren = rootElement.getChildren();
        if (children.isEmpty()) {
            return;
        }
        for (Element child : children) {
            if (child.getName().equals()) {
                .add(child.getValue());
            }
            if (!child.getChildren().isEmpty()) {
                processCapabilities(child);
            }
        }
    }
    private void printPrettyXML(String xmlstring) {
        try {
            Document doc = new SAXBuilder().build(new StringReader(xmlstring));
            XMLOutputter xmOut = new XMLOutputter(Format.getPrettyFormat());
            String outputString = xmOut.outputString(doc);
            .debug(outputString);
        } catch (Exception e) {
            .error("ERROR while parsing the XML " + xmlstringe);
        }
    }

    
This would return host IP and host Port, used by this particular Netconf Device.

Returns:
Device Information.
    public String deviceInfo() {
        return new StringBuilder("host: ").append().append(". port: ")
                .append().toString();
    }

    
This will terminate the device connection.
    public void disconnect() {
        .close();
         = false;
    }

    
This will list down all the capabilities supported on the device.

Returns:
Capability list.
    public List<StringgetCapabilities() {
        return ;
    }

    
This api is intended to know whether the device is connected or not.

Returns:
true if connected
    public boolean isReachable() {
        return ;
    }

    
This will return the IP used connect ssh on the device.

Returns:
Netconf Device IP
    public String getSshHost() {
        return ;
    }

    
This will return the SSH Port used connect the device.

Returns:
SSH Port number
    public int getSshPort() {
        return ;
    }

    
The usename used to connect Netconf Device.

Returns:
Device Username
    public String getUsername() {
        return ;
    }

    
Retrieve current state of the device.

Returns:
Current Device State
    public DeviceState getDeviceState() {
        return ;
    }

    
This is set the state information for the device.

Parameters:
deviceState Next Device State
    public void setDeviceState(DeviceState deviceState) {
        this. = deviceState;
    }

    
Check whether the device is in Active state.

Returns:
true if the device is Active
    public boolean isActive() {
        return  == . ? true : false;
    }
    public void setConnectTimeout(int connectTimeout) {
        this. = connectTimeout;
    }
New to GrepCode? Check out our FAQ X