Simplify boolean expressions
[netconf.git] / netconf / netconf-console / src / main / java / org / opendaylight / netconf / console / impl / NetconfCommandsImpl.java
1 /*
2  * Copyright (c) 2016 Inocybe Technologies 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.netconf.console.impl;
10
11 import com.google.common.base.Strings;
12 import com.google.common.collect.ImmutableList;
13 import com.google.common.util.concurrent.FutureCallback;
14 import com.google.common.util.concurrent.Futures;
15 import java.util.ArrayList;
16 import java.util.HashMap;
17 import java.util.List;
18 import java.util.Map;
19 import java.util.UUID;
20 import java.util.stream.Collectors;
21 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
22 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
23 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
24 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
25 import org.opendaylight.netconf.console.api.NetconfCommands;
26 import org.opendaylight.netconf.console.utils.NetconfConsoleConstants;
27 import org.opendaylight.netconf.console.utils.NetconfConsoleUtils;
28 import org.opendaylight.netconf.console.utils.NetconfIidFactory;
29 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Host;
30 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
31 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Address;
32 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.PortNumber;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNode;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNodeBuilder;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.status.available.capabilities.AvailableCapability;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.Credentials;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.credentials.LoginPasswordBuilder;
38 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
39 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology;
40 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
41 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeBuilder;
42 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeKey;
43 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
46
47 public class NetconfCommandsImpl implements NetconfCommands {
48
49     private static final Logger LOG = LoggerFactory.getLogger(NetconfCommandsImpl.class);
50
51     private final DataBroker dataBroker;
52
53     public NetconfCommandsImpl(final DataBroker db) {
54         LOG.debug("NetconfConsoleProviderImpl initialized");
55         this.dataBroker = db;
56     }
57
58     @Override
59     public Map<String, Map<String, String>> listDevices() {
60         final Topology topology = NetconfConsoleUtils.read(LogicalDatastoreType.OPERATIONAL,
61                 NetconfIidFactory.NETCONF_TOPOLOGY_IID, dataBroker);
62         if (topology == null) {
63             return new HashMap<>();
64         }
65         final Map<String, Map<String, String>> netconfNodes = new HashMap<>();
66         for (final Node node : topology.getNode()) {
67             final NetconfNode netconfNode = node.getAugmentation(NetconfNode.class);
68             final Map<String, String> attributes = new HashMap<>();
69             attributes.put(NetconfConsoleConstants.NETCONF_ID, node.getNodeId().getValue());
70             attributes.put(NetconfConsoleConstants.NETCONF_IP,
71                     netconfNode.getHost().getIpAddress().getIpv4Address().getValue());
72             attributes.put(NetconfConsoleConstants.NETCONF_PORT, netconfNode.getPort().getValue().toString());
73             attributes.put(NetconfConsoleConstants.STATUS, netconfNode.getConnectionStatus().name().toLowerCase());
74             netconfNodes.put(node.getNodeId().getValue(), attributes);
75         }
76         return netconfNodes;
77     }
78
79     @Override
80     public Map<String, Map<String, List<String>>> showDevice(final String deviceIp, final String devicePort) {
81         final Map<String, Map<String, List<String>>> device = new HashMap<>();
82         List<Node> nodeList = new ArrayList<>();
83         if (devicePort != null) {
84             nodeList.add(NetconfConsoleUtils.getNetconfNodeFromIpAndPort(deviceIp, devicePort, dataBroker));
85         } else {
86             nodeList = NetconfConsoleUtils.getNetconfNodeFromId(deviceIp, dataBroker);
87         }
88         if (nodeList != null) {
89             for (final Node node : nodeList) {
90                 if (node != null) {
91                     final NetconfNode netconfNode = node.getAugmentation(NetconfNode.class);
92                     final Map<String, List<String>> attributes = new HashMap<>();
93                     attributes.put(NetconfConsoleConstants.NETCONF_ID, ImmutableList.of(node.getNodeId().getValue()));
94                     attributes.put(NetconfConsoleConstants.NETCONF_IP,
95                             ImmutableList.of(netconfNode.getHost().getIpAddress().getIpv4Address().getValue()));
96                     attributes.put(NetconfConsoleConstants.NETCONF_PORT,
97                             ImmutableList.of(netconfNode.getPort().getValue().toString()));
98                     attributes.put(NetconfConsoleConstants.STATUS,
99                             ImmutableList.of(netconfNode.getConnectionStatus().name()));
100                     attributes.put(NetconfConsoleConstants.AVAILABLE_CAPABILITIES,
101                             netconfNode.getAvailableCapabilities().getAvailableCapability().stream()
102                                     .map(AvailableCapability::getCapability).collect(Collectors.toList()));
103                     device.put(node.getNodeId().getValue(), attributes);
104                 }
105             }
106         }
107         return device;
108     }
109
110     @Override
111     public Map<String, Map<String, List<String>>> showDevice(final String deviceId) {
112         final Map<String, Map<String, List<String>>> device = new HashMap<>();
113         final List<Node> nodeList = NetconfConsoleUtils.getNetconfNodeFromId(deviceId, dataBroker);
114         if (nodeList != null && nodeList.size() > 0) {
115             for (final Node node : nodeList) {
116                 final NetconfNode netconfNode = node.getAugmentation(NetconfNode.class);
117                 final Map<String, List<String>> attributes = new HashMap<>();
118                 attributes.put(NetconfConsoleConstants.NETCONF_ID, ImmutableList.of(node.getNodeId().getValue()));
119                 attributes.put(NetconfConsoleConstants.NETCONF_IP,
120                         ImmutableList.of(netconfNode.getHost().getIpAddress().getIpv4Address().getValue()));
121                 attributes.put(NetconfConsoleConstants.NETCONF_PORT,
122                         ImmutableList.of(netconfNode.getPort().getValue().toString()));
123                 attributes.put(NetconfConsoleConstants.STATUS,
124                         ImmutableList.of(netconfNode.getConnectionStatus().name()));
125                 attributes.put(NetconfConsoleConstants.AVAILABLE_CAPABILITIES,
126                         netconfNode.getAvailableCapabilities().getAvailableCapability().stream()
127                                 .map(AvailableCapability::getCapability).collect(Collectors.toList()));
128                 device.put(node.getNodeId().getValue(), attributes);
129             }
130         }
131         return device;
132     }
133
134     @Override
135     public void connectDevice(NetconfNode netconfNode, String netconfNodeId) {
136         final NodeId nodeId;
137         if (!Strings.isNullOrEmpty(netconfNodeId)) {
138             nodeId = new NodeId(netconfNodeId);
139         } else {
140             nodeId = new NodeId(UUID.randomUUID().toString().replace("-", ""));
141         }
142         final Node node = new NodeBuilder()
143                 .setKey(new NodeKey(nodeId))
144                 .setNodeId(nodeId)
145                 .addAugmentation(NetconfNode.class, netconfNode)
146                 .build();
147
148         final WriteTransaction transaction = dataBroker.newWriteOnlyTransaction();
149         transaction.put(LogicalDatastoreType.CONFIGURATION, NetconfIidFactory.netconfNodeIid(nodeId.getValue()), node);
150
151         Futures.addCallback(transaction.submit(), new FutureCallback<Void>() {
152
153             @Override
154             public void onSuccess(Void result) {
155                 LOG.debug("NetconfNode={} created successfully", netconfNode);
156             }
157
158             @Override
159             public void onFailure(Throwable throwable) {
160                 LOG.error("Failed to created NetconfNode={}", netconfNode);
161                 throw new RuntimeException(throwable);
162             }
163         });
164     }
165
166     @Override
167     public boolean disconnectDevice(String netconfNodeId) {
168         boolean result = false;
169         final WriteTransaction transaction = dataBroker.newWriteOnlyTransaction();
170         InstanceIdentifier<Node> iid = NetconfIidFactory.netconfNodeIid(netconfNodeId);
171         transaction.delete(LogicalDatastoreType.CONFIGURATION, iid);
172
173         try {
174             LOG.debug("Deleting netconf node: {}", netconfNodeId);
175             transaction.submit().checkedGet();
176             result = true;
177         } catch (final TransactionCommitFailedException e) {
178             LOG.error("Unable to remove node with Iid {}", iid, e);
179         }
180         return result;
181     }
182
183     @Override
184     public boolean disconnectDevice(final String deviceIp, final String devicePort) {
185         final String netconfNodeId = NetconfConsoleUtils
186                 .getNetconfNodeFromIpAndPort(deviceIp, devicePort, dataBroker).getNodeId().getValue();
187         return disconnectDevice(netconfNodeId);
188     }
189
190     @Override
191     public String updateDevice(final String netconfNodeId, String username, String password,
192                                Map<String, String> updated) {
193         final Node node = NetconfConsoleUtils
194                 .read(LogicalDatastoreType.OPERATIONAL, NetconfIidFactory.netconfNodeIid(netconfNodeId), dataBroker);
195
196         if (node != null && node.getAugmentation(NetconfNode.class) != null) {
197             final NetconfNode netconfNode = node.getAugmentation(NetconfNode.class);
198
199             // Get NETCONF attributes to update if present else get their original values from NetconfNode instance
200             final String deviceIp = Strings.isNullOrEmpty(updated.get(NetconfConsoleConstants.NETCONF_IP))
201                     ? netconfNode.getHost().getIpAddress().getIpv4Address().getValue()
202                     : updated.get(NetconfConsoleConstants.NETCONF_IP);
203             final String devicePort = Strings.isNullOrEmpty(updated.get(NetconfConsoleConstants.NETCONF_PORT))
204                     ? netconfNode.getPort().getValue().toString() : updated.get(NetconfConsoleConstants.NETCONF_PORT);
205             final Boolean tcpOnly = updated.get(NetconfConsoleConstants.TCP_ONLY).equals("true");
206             final Boolean isSchemaless =
207                     updated.get(NetconfConsoleConstants.SCHEMALESS).equals("true");
208             final String newUsername = Strings.isNullOrEmpty(updated.get(NetconfConsoleConstants.USERNAME))
209                     ? updated.get(NetconfConsoleConstants.USERNAME) : username;
210             final String newPassword = Strings.isNullOrEmpty(updated.get(NetconfConsoleConstants.PASSWORD))
211                     ? updated.get(NetconfConsoleConstants.PASSWORD) : password;
212
213             final Credentials credentials =
214                     new LoginPasswordBuilder().setPassword(newPassword).setUsername(newUsername).build();
215             final NetconfNode updatedNetconfNode = new NetconfNodeBuilder()
216                     .setHost(new Host(new IpAddress(new Ipv4Address(deviceIp))))
217                     .setPort(new PortNumber(Integer.decode(devicePort)))
218                     .setTcpOnly(tcpOnly)
219                     .setSchemaless(isSchemaless)
220                     .setCredentials(credentials)
221                     .build();
222
223             final Node updatedNode = new NodeBuilder()
224                     .setKey(node.getKey())
225                     .setNodeId(node.getNodeId())
226                     .addAugmentation(NetconfNode.class, updatedNetconfNode)
227                     .build();
228
229             final WriteTransaction transaction = dataBroker.newWriteOnlyTransaction();
230             transaction.put(LogicalDatastoreType.CONFIGURATION,
231                     NetconfIidFactory.netconfNodeIid(updatedNode.getNodeId().getValue()), updatedNode);
232
233             Futures.addCallback(transaction.submit(), new FutureCallback<Void>() {
234
235                 @Override
236                 public void onSuccess(Void result) {
237                     LOG.debug("NetconfNode={} updated successfully", netconfNode);
238                 }
239
240                 @Override
241                 public void onFailure(Throwable throwable) {
242                     LOG.error("Failed to updated NetconfNode={}", netconfNode);
243                     throw new RuntimeException(throwable);
244                 }
245             });
246
247             return "NETCONF node: " + netconfNodeId + " updated successfully.";
248         } else {
249             return "NETCONF node: " + netconfNodeId + " does not exist to update";
250         }
251     }
252 }