Fix to set/delete Switch Configuration using Northbound API
[controller.git] / opendaylight / web / devices / src / main / java / org / opendaylight / controller / devices / web / Devices.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.devices.web;
10
11 import java.util.ArrayList;
12 import java.util.HashMap;
13 import java.util.HashSet;
14 import java.util.List;
15 import java.util.Map;
16 import java.util.Map.Entry;
17 import java.util.Set;
18 import java.util.TreeMap;
19 import java.util.concurrent.ConcurrentMap;
20
21 import javax.servlet.http.HttpServletRequest;
22 import javax.servlet.http.HttpServletResponse;
23
24 import org.codehaus.jackson.map.ObjectMapper;
25 import org.opendaylight.controller.forwarding.staticrouting.IForwardingStaticRouting;
26 import org.opendaylight.controller.forwarding.staticrouting.StaticRouteConfig;
27 import org.opendaylight.controller.sal.authorization.Privilege;
28 import org.opendaylight.controller.sal.authorization.UserLevel;
29 import org.opendaylight.controller.sal.core.Config;
30 import org.opendaylight.controller.sal.core.Description;
31 import org.opendaylight.controller.sal.core.ForwardingMode;
32 import org.opendaylight.controller.sal.core.Name;
33 import org.opendaylight.controller.sal.core.Node;
34 import org.opendaylight.controller.sal.core.NodeConnector;
35 import org.opendaylight.controller.sal.core.Property;
36 import org.opendaylight.controller.sal.core.State;
37 import org.opendaylight.controller.sal.core.Tier;
38 import org.opendaylight.controller.sal.utils.GlobalConstants;
39 import org.opendaylight.controller.sal.utils.HexEncode;
40 import org.opendaylight.controller.sal.utils.ServiceHelper;
41 import org.opendaylight.controller.sal.utils.Status;
42 import org.opendaylight.controller.sal.utils.TierHelper;
43 import org.opendaylight.controller.switchmanager.ISwitchManager;
44 import org.opendaylight.controller.switchmanager.SpanConfig;
45 import org.opendaylight.controller.switchmanager.SubnetConfig;
46 import org.opendaylight.controller.switchmanager.Switch;
47 import org.opendaylight.controller.switchmanager.SwitchConfig;
48 import org.opendaylight.controller.web.DaylightWebUtil;
49 import org.opendaylight.controller.web.IDaylightWeb;
50 import org.springframework.stereotype.Controller;
51 import org.springframework.web.bind.annotation.RequestMapping;
52 import org.springframework.web.bind.annotation.RequestMethod;
53 import org.springframework.web.bind.annotation.RequestParam;
54 import org.springframework.web.bind.annotation.ResponseBody;
55
56 import com.google.gson.Gson;
57
58 @Controller
59 @RequestMapping("/")
60 public class Devices implements IDaylightWeb {
61     private static final UserLevel AUTH_LEVEL = UserLevel.CONTAINERUSER;
62     private final String WEB_NAME = "Devices";
63     private final String WEB_ID = "devices";
64     private final short WEB_ORDER = 1;
65
66     public Devices() {
67         ServiceHelper.registerGlobalService(IDaylightWeb.class, this, null);
68     }
69
70     @Override
71     public String getWebName() {
72         return WEB_NAME;
73     }
74
75     @Override
76     public String getWebId() {
77         return WEB_ID;
78     }
79
80     @Override
81     public short getWebOrder() {
82         return WEB_ORDER;
83     }
84
85     @Override
86     public boolean isAuthorized(UserLevel userLevel) {
87         return userLevel.ordinal() <= AUTH_LEVEL.ordinal();
88     }
89
90     @RequestMapping(value = "/nodesLearnt", method = RequestMethod.GET)
91     @ResponseBody
92     public DevicesJsonBean getNodesLearnt(HttpServletRequest request,
93             @RequestParam(required = false) String container) {
94         Gson gson = new Gson();
95         String containerName = (container == null) ? GlobalConstants.DEFAULT
96                 .toString() : container;
97
98         // Derive the privilege this user has on the current container
99         String userName = request.getUserPrincipal().getName();
100         Privilege privilege = DaylightWebUtil.getContainerPrivilege(userName, containerName, this);
101
102         ISwitchManager switchManager = (ISwitchManager) ServiceHelper.getInstance(ISwitchManager.class, containerName,
103                 this);
104         List<Map<String, String>> nodeData = new ArrayList<Map<String, String>>();
105         if (switchManager != null && privilege != Privilege.NONE) {
106             for (Switch device : switchManager.getNetworkDevices()) {
107                 HashMap<String, String> nodeDatum = new HashMap<String, String>();
108                 Node node = device.getNode();
109                 Tier tier = (Tier) switchManager.getNodeProp(node, Tier.TierPropName);
110                 nodeDatum.put("containerName", containerName);
111                 Description description = (Description) switchManager.getNodeProp(node, Description.propertyName);
112                 String desc = (description == null) ? "" : description.getValue();
113                 nodeDatum.put("nodeName", desc);
114                 nodeDatum.put("nodeId", node.toString());
115                 int tierNumber = (tier == null) ? TierHelper.unknownTierNumber : tier.getValue();
116                 nodeDatum.put("tierName", TierHelper.getTierName(tierNumber) + " (Tier-" + tierNumber + ")");
117                 nodeDatum.put("tier", tierNumber + "");
118                 String modeStr = "0";
119                 ForwardingMode mode = null;
120                 if (!containerName.equals(GlobalConstants.DEFAULT.toString())) {
121                     ISwitchManager switchManagerDefault = (ISwitchManager) ServiceHelper.getInstance(
122                             ISwitchManager.class, GlobalConstants.DEFAULT.toString(), this);
123                     mode = (ForwardingMode) switchManagerDefault.getNodeProp(node, ForwardingMode.name);
124                 } else {
125                     mode = (ForwardingMode) switchManager.getNodeProp(node, ForwardingMode.name);
126                 }
127                 if (mode != null) {
128                     modeStr = String.valueOf(mode.getValue());
129                 }
130                 nodeDatum.put("mode", modeStr);
131
132                 nodeDatum.put("json", gson.toJson(nodeDatum));
133                 nodeDatum.put("mac", HexEncode.bytesToHexString(device.getDataLayerAddress()));
134                 StringBuffer sb1 = new StringBuffer();
135                 Set<NodeConnector> nodeConnectorSet = device.getNodeConnectors();
136                 if (nodeConnectorSet != null && nodeConnectorSet.size() > 0) {
137                     Map<Short, String> portList = new HashMap<Short, String>();
138                     List<String> intfList = new ArrayList<String>();
139                     for (NodeConnector nodeConnector : nodeConnectorSet) {
140                         String nodeConnectorNumberToStr = nodeConnector.getID().toString();
141                         Name ncName = ((Name) switchManager.getNodeConnectorProp(nodeConnector, Name.NamePropName));
142                         Config portStatus = ((Config) switchManager
143                                 .getNodeConnectorProp(nodeConnector,
144                                         Config.ConfigPropName));
145                         State portState = ((State) switchManager
146                                 .getNodeConnectorProp(nodeConnector,
147                                         State.StatePropName));
148
149                         String nodeConnectorName = (ncName != null) ? ncName
150                                 .getValue() : "";
151                         nodeConnectorName += " (" + nodeConnector.getID() + ")";
152
153                         if (portStatus != null) {
154                             if (portStatus.getValue() == Config.ADMIN_UP) {
155                                 if (portState.getValue() == State.EDGE_UP) {
156                                     nodeConnectorName = "<span class='admin-up'>"
157                                             + nodeConnectorName + "</span>";
158                                 } else if (portState.getValue() == State.EDGE_DOWN) {
159                                     nodeConnectorName = "<span class='edge-down'>"
160                                             + nodeConnectorName + "</span>";
161                                 }
162                             } else if (portStatus.getValue() == Config.ADMIN_DOWN) {
163                                 nodeConnectorName = "<span class='admin-down'>"
164                                         + nodeConnectorName + "</span>";
165                             }
166                         }
167
168                         Class<?> idClass = nodeConnector.getID().getClass();
169                         if (idClass.equals(Short.class)) {
170                             portList.put(
171                                     Short.parseShort(nodeConnectorNumberToStr),
172                                     nodeConnectorName);
173                         } else {
174                             intfList.add(nodeConnectorName);
175                         }
176                     }
177
178                     if (portList.size() > 0) {
179                         Map<Short, String> sortedPortList = new TreeMap<Short, String>(
180                                 portList);
181
182                         for (Entry<Short, String> e : sortedPortList.entrySet()) {
183                             sb1.append(e.getValue());
184                             sb1.append("<br>");
185                         }
186                     } else if (intfList.size() > 0) {
187                         for (String intf : intfList) {
188                             sb1.append(intf);
189                             sb1.append("<br>");
190                         }
191                     }
192                 }
193                 nodeDatum.put("ports", sb1.toString());
194                 nodeData.add(nodeDatum);
195             }
196         }
197
198         DevicesJsonBean result = new DevicesJsonBean();
199         result.setNodeData(nodeData);
200         result.setPrivilege(privilege);
201         List<String> columnNames = new ArrayList<String>();
202         columnNames.add("Node ID");
203         columnNames.add("Node Name");
204         columnNames.add("Tier");
205         columnNames.add("Mac Address");
206         columnNames.add("Ports");
207         columnNames.add("Port Status");
208
209         result.setColumnNames(columnNames);
210         return result;
211     }
212
213     @RequestMapping(value = "/tiers", method = RequestMethod.GET)
214     @ResponseBody
215     public List<String> getTiers() {
216         return TierHelper.getTiers();
217     }
218
219     @RequestMapping(value = "/nodesLearnt/update", method = RequestMethod.GET)
220     @ResponseBody
221     public StatusJsonBean updateLearntNode(
222             @RequestParam("nodeName") String nodeName,
223             @RequestParam("nodeId") String nodeId,
224             @RequestParam("tier") String tier,
225             @RequestParam("operationMode") String operationMode,
226             HttpServletRequest request,
227             @RequestParam(required = false) String container) {
228         String containerName = (container == null) ? GlobalConstants.DEFAULT
229                 .toString() : container;
230
231         // Authorization check
232         String userName = request.getUserPrincipal().getName();
233         if (DaylightWebUtil
234                 .getContainerPrivilege(userName, containerName, this) != Privilege.WRITE) {
235             return unauthorizedMessage();
236         }
237
238         StatusJsonBean resultBean = new StatusJsonBean();
239         try {
240             ISwitchManager switchManager = (ISwitchManager) ServiceHelper
241                     .getInstance(ISwitchManager.class, containerName, this);
242             Map<String, Property> nodeProperties = new HashMap<String, Property>();
243             Property desc = new Description(nodeName);
244             nodeProperties.put(desc.getName(), desc);
245             Property nodeTier = new Tier(Integer.parseInt(tier));
246             nodeProperties.put(nodeTier.getName(), nodeTier);
247             if (containerName.equals(GlobalConstants.DEFAULT.toString())) {
248                 Property mode = new ForwardingMode(Integer.parseInt(operationMode));
249                 nodeProperties.put(mode.getName(), mode);
250             }
251             SwitchConfig cfg = new SwitchConfig(nodeId, nodeProperties);
252             Status result = switchManager.updateNodeConfig(cfg);
253             if (!result.isSuccess()) {
254                 resultBean.setStatus(false);
255                 resultBean.setMessage(result.getDescription());
256             } else {
257                 resultBean.setStatus(true);
258                 resultBean.setMessage("Updated node information successfully");
259             }
260         } catch (Exception e) {
261             resultBean.setStatus(false);
262             resultBean.setMessage("Error updating node information. "
263                     + e.getMessage());
264         }
265         return resultBean;
266     }
267
268     @RequestMapping(value = "/staticRoutes", method = RequestMethod.GET)
269     @ResponseBody
270     public DevicesJsonBean getStaticRoutes(HttpServletRequest request,
271             @RequestParam(required = false) String container) {
272         Gson gson = new Gson();
273         String containerName = (container == null) ? GlobalConstants.DEFAULT
274                 .toString() : container;
275
276         // Derive the privilege this user has on the current container
277         String userName = request.getUserPrincipal().getName();
278         Privilege privilege = DaylightWebUtil.getContainerPrivilege(userName, containerName, this);
279
280         IForwardingStaticRouting staticRouting = (IForwardingStaticRouting) ServiceHelper
281                 .getInstance(IForwardingStaticRouting.class, containerName,
282                         this);
283         if (staticRouting == null) {
284             return null;
285         }
286         List<Map<String, String>> staticRoutes = new ArrayList<Map<String, String>>();
287         ConcurrentMap<String, StaticRouteConfig> routeConfigs = staticRouting
288                 .getStaticRouteConfigs();
289         if (routeConfigs == null) {
290             return null;
291         }
292         if (privilege != Privilege.NONE) {
293             for (StaticRouteConfig conf : routeConfigs.values()) {
294                 Map<String, String> staticRoute = new HashMap<String, String>();
295                 staticRoute.put("name", conf.getName());
296                 staticRoute.put("staticRoute", conf.getStaticRoute());
297                 staticRoute.put("nextHopType", conf.getNextHopType());
298                 staticRoute.put("nextHop", conf.getNextHop());
299                 staticRoute.put("json", gson.toJson(conf));
300                 staticRoutes.add(staticRoute);
301             }
302         }
303         DevicesJsonBean result = new DevicesJsonBean();
304         result.setPrivilege(privilege);
305         result.setColumnNames(StaticRouteConfig.getGuiFieldsNames());
306         result.setNodeData(staticRoutes);
307         return result;
308     }
309
310     @RequestMapping(value = "/staticRoute/add", method = RequestMethod.GET)
311     @ResponseBody
312     public StatusJsonBean addStaticRoute(
313             @RequestParam("routeName") String routeName,
314             @RequestParam("staticRoute") String staticRoute,
315             @RequestParam("nextHop") String nextHop,
316             HttpServletRequest request,
317             @RequestParam(required = false) String container) {
318         String containerName = (container == null) ? GlobalConstants.DEFAULT
319                 .toString() : container;
320
321         // Authorization check
322         String userName = request.getUserPrincipal().getName();
323         if (DaylightWebUtil
324                 .getContainerPrivilege(userName, containerName, this) != Privilege.WRITE) {
325             return unauthorizedMessage();
326         }
327
328         StatusJsonBean result = new StatusJsonBean();
329         try {
330             IForwardingStaticRouting staticRouting = (IForwardingStaticRouting) ServiceHelper
331                     .getInstance(IForwardingStaticRouting.class, containerName,
332                             this);
333             StaticRouteConfig config = new StaticRouteConfig();
334             config.setName(routeName);
335             config.setStaticRoute(staticRoute);
336             config.setNextHop(nextHop);
337             Status addStaticRouteResult = staticRouting.addStaticRoute(config);
338             if (addStaticRouteResult.isSuccess()) {
339                 result.setStatus(true);
340                 result.setMessage("Static Route saved successfully");
341             } else {
342                 result.setStatus(false);
343                 result.setMessage(addStaticRouteResult.getDescription());
344             }
345         } catch (Exception e) {
346             result.setStatus(false);
347             result.setMessage("Error - " + e.getMessage());
348         }
349         return result;
350     }
351
352     @RequestMapping(value = "/staticRoute/delete", method = RequestMethod.GET)
353     @ResponseBody
354     public StatusJsonBean deleteStaticRoute(
355             @RequestParam("routesToDelete") String routesToDelete,
356             HttpServletRequest request,
357             @RequestParam(required = false) String container) {
358         String containerName = (container == null) ? GlobalConstants.DEFAULT
359                 .toString() : container;
360
361         // Authorization check
362         String userName = request.getUserPrincipal().getName();
363         if (DaylightWebUtil.getContainerPrivilege(userName, containerName, this) != Privilege.WRITE) {
364             return unauthorizedMessage();
365         }
366
367         StatusJsonBean resultBean = new StatusJsonBean();
368         try {
369             IForwardingStaticRouting staticRouting = (IForwardingStaticRouting) ServiceHelper
370                     .getInstance(IForwardingStaticRouting.class, containerName,
371                             this);
372             String[] routes = routesToDelete.split(",");
373             Status result;
374             resultBean.setStatus(true);
375             resultBean
376                     .setMessage("Successfully deleted selected static routes");
377             for (String route : routes) {
378                 result = staticRouting.removeStaticRoute(route);
379                 if (!result.isSuccess()) {
380                     resultBean.setStatus(false);
381                     resultBean.setMessage(result.getDescription());
382                     break;
383                 }
384             }
385         } catch (Exception e) {
386             resultBean.setStatus(false);
387             resultBean
388                     .setMessage("Error occurred while deleting static routes. "
389                             + e.getMessage());
390         }
391         return resultBean;
392     }
393
394     @RequestMapping(value = "/subnets", method = RequestMethod.GET)
395     @ResponseBody
396     public DevicesJsonBean getSubnetGateways(HttpServletRequest request,
397             @RequestParam(required = false) String container) {
398         Gson gson = new Gson();
399         List<Map<String, String>> subnets = new ArrayList<Map<String, String>>();
400         String containerName = (container == null) ? GlobalConstants.DEFAULT
401                 .toString() : container;
402
403         // Derive the privilege this user has on the current container
404         String userName = request.getUserPrincipal().getName();
405         Privilege privilege = DaylightWebUtil.getContainerPrivilege(
406                 userName, containerName, this);
407
408         if (privilege != Privilege.NONE) {
409             ISwitchManager switchManager = (ISwitchManager) ServiceHelper
410                     .getInstance(ISwitchManager.class, containerName, this);
411             if (switchManager != null) {
412                 for (SubnetConfig conf : switchManager.getSubnetsConfigList()) {
413                     Map<String, String> subnet = new HashMap<String, String>();
414                     subnet.put("name", conf.getName());
415                     subnet.put("subnet", conf.getSubnet());
416                     subnet.put("json", gson.toJson(conf));
417                     subnets.add(subnet);
418                 }
419             }
420         }
421         DevicesJsonBean result = new DevicesJsonBean();
422         result.setPrivilege(privilege);
423         result.setColumnNames(SubnetConfig.getGuiFieldsNames());
424         result.setNodeData(subnets);
425         return result;
426     }
427
428     @RequestMapping(value = "/subnetGateway/add", method = RequestMethod.GET)
429     @ResponseBody
430     public StatusJsonBean addSubnetGateways(
431             @RequestParam("gatewayName") String gatewayName,
432             @RequestParam("gatewayIPAddress") String gatewayIPAddress,
433             HttpServletRequest request,
434             @RequestParam(required = false) String container) {
435         String containerName = (container == null) ? GlobalConstants.DEFAULT
436                 .toString() : container;
437
438         // Authorization check
439         String userName = request.getUserPrincipal().getName();
440         if (DaylightWebUtil.getContainerPrivilege(userName, containerName, this) != Privilege.WRITE) {
441             return unauthorizedMessage();
442         }
443
444         StatusJsonBean resultBean = new StatusJsonBean();
445         try {
446             ISwitchManager switchManager = (ISwitchManager) ServiceHelper
447                     .getInstance(ISwitchManager.class, containerName, this);
448             SubnetConfig cfgObject = new SubnetConfig(gatewayName,
449                     gatewayIPAddress, new HashSet<String>());
450             Status result = switchManager.addSubnet(cfgObject);
451             if (result.isSuccess()) {
452                 resultBean.setStatus(true);
453                 resultBean.setMessage("Added gateway address successfully");
454             } else {
455                 resultBean.setStatus(false);
456                 resultBean.setMessage(result.getDescription());
457             }
458         } catch (Exception e) {
459             resultBean.setStatus(false);
460             resultBean.setMessage(e.getMessage());
461         }
462         return resultBean;
463     }
464
465     @RequestMapping(value = "/subnetGateway/delete", method = RequestMethod.GET)
466     @ResponseBody
467     public StatusJsonBean deleteSubnetGateways(
468             @RequestParam("gatewaysToDelete") String gatewaysToDelete,
469             HttpServletRequest request,
470             @RequestParam(required = false) String container) {
471         String containerName = (container == null) ? GlobalConstants.DEFAULT
472                 .toString() : container;
473
474         // Authorization check
475         String userName = request.getUserPrincipal().getName();
476         if (DaylightWebUtil.getContainerPrivilege(userName, container, this) != Privilege.WRITE) {
477             return unauthorizedMessage();
478         }
479
480         StatusJsonBean resultBean = new StatusJsonBean();
481         try {
482             ISwitchManager switchManager = (ISwitchManager) ServiceHelper
483                     .getInstance(ISwitchManager.class, containerName, this);
484             String[] subnets = gatewaysToDelete.split(",");
485             resultBean.setStatus(true);
486             resultBean.setMessage("Added gateway address successfully");
487             for (String subnet : subnets) {
488                 Status result = switchManager.removeSubnet(subnet);
489                 if (!result.isSuccess()) {
490                     resultBean.setStatus(false);
491                     resultBean.setMessage(result.getDescription());
492                     break;
493                 }
494             }
495         } catch (Exception e) {
496             resultBean.setStatus(false);
497             resultBean.setMessage(e.getMessage());
498         }
499         return resultBean;
500     }
501
502     @RequestMapping(value = "/subnetGateway/ports/add", method = RequestMethod.GET)
503     @ResponseBody
504     public StatusJsonBean addSubnetGatewayPort(
505             @RequestParam("portsName") String portsName,
506             @RequestParam("ports") String ports,
507             @RequestParam("nodeId") String nodeId, HttpServletRequest request,
508             @RequestParam(required = false) String container) {
509         String containerName = (container == null) ? GlobalConstants.DEFAULT
510                 .toString() : container;
511
512         // Authorization check
513         String userName = request.getUserPrincipal().getName();
514         if (DaylightWebUtil.getContainerPrivilege(userName, containerName, this) != Privilege.WRITE) {
515             return unauthorizedMessage();
516         }
517
518         StatusJsonBean resultBean = new StatusJsonBean();
519         try {
520             ISwitchManager switchManager = (ISwitchManager) ServiceHelper
521                     .getInstance(ISwitchManager.class, containerName, this);
522             Status result = switchManager.addPortsToSubnet(portsName, nodeId
523                     + "/" + ports);
524
525             if (result.isSuccess()) {
526                 resultBean.setStatus(true);
527                 resultBean
528                         .setMessage("Added ports to subnet gateway address successfully");
529             } else {
530                 resultBean.setStatus(false);
531                 resultBean.setMessage(result.getDescription());
532             }
533         } catch (Exception e) {
534             resultBean.setStatus(false);
535             resultBean.setMessage(e.getMessage());
536         }
537         return resultBean;
538     }
539
540     @RequestMapping(value = "/subnetGateway/ports/delete", method = RequestMethod.GET)
541     @ResponseBody
542     public StatusJsonBean deleteSubnetGatewayPort(
543             @RequestParam("gatewayName") String gatewayName,
544             @RequestParam("nodePort") String nodePort,
545             HttpServletRequest request,
546             @RequestParam(required = false) String container) {
547         String containerName = (container == null) ? GlobalConstants.DEFAULT
548                 .toString() : container;
549
550         // Authorization check
551         String userName = request.getUserPrincipal().getName();
552         if (DaylightWebUtil.getContainerPrivilege(userName, containerName, this) != Privilege.WRITE) {
553             return unauthorizedMessage();
554         }
555
556         StatusJsonBean resultBean = new StatusJsonBean();
557         try {
558             ISwitchManager switchManager = (ISwitchManager) ServiceHelper
559                     .getInstance(ISwitchManager.class, containerName, this);
560             Status result = switchManager.removePortsFromSubnet(gatewayName,
561                     nodePort);
562
563             if (result.isSuccess()) {
564                 resultBean.setStatus(true);
565                 resultBean
566                         .setMessage("Deleted port from subnet gateway address successfully");
567             } else {
568                 resultBean.setStatus(false);
569                 resultBean.setMessage(result.getDescription());
570             }
571         } catch (Exception e) {
572             resultBean.setStatus(false);
573             resultBean.setMessage(e.getMessage());
574         }
575         return resultBean;
576     }
577
578     @RequestMapping(value = "/spanPorts", method = RequestMethod.GET)
579     @ResponseBody
580     public DevicesJsonBean getSpanPorts(HttpServletRequest request,
581             @RequestParam(required = false) String container) {
582         Gson gson = new Gson();
583         List<Map<String, String>> spanConfigs = new ArrayList<Map<String, String>>();
584         String containerName = (container == null) ? GlobalConstants.DEFAULT
585                 .toString() : container;
586
587         // Derive the privilege this user has on the current container
588         String userName = request.getUserPrincipal().getName();
589         Privilege privilege = DaylightWebUtil.getContainerPrivilege(
590                 userName, containerName, this);
591
592         if (privilege != Privilege.NONE) {
593             List<String> spanConfigs_json = new ArrayList<String>();
594             ISwitchManager switchManager = (ISwitchManager) ServiceHelper
595                     .getInstance(ISwitchManager.class, containerName, this);
596             if (switchManager != null) {
597                 for (SpanConfig conf : switchManager.getSpanConfigList()) {
598                     spanConfigs_json.add(gson.toJson(conf));
599                 }
600             }
601             ObjectMapper mapper = new ObjectMapper();
602
603             for (String config_json : spanConfigs_json) {
604                 try {
605                     @SuppressWarnings("unchecked")
606                     Map<String, String> config_data = mapper.readValue(config_json,
607                             HashMap.class);
608                     Map<String, String> config = new HashMap<String, String>();
609                     for (String name : config_data.keySet()) {
610                         config.put(name, config_data.get(name));
611                         // Add switch name value (non-configuration field)
612                         config.put("nodeName",
613                                 getNodeDesc(config_data.get("nodeId"), containerName));
614                     }
615                     config.put("json", config_json);
616                     spanConfigs.add(config);
617                 } catch (Exception e) {
618                     // TODO: Handle the exception.
619                 }
620             }
621         }
622
623         DevicesJsonBean result = new DevicesJsonBean();
624         result.setPrivilege(privilege);
625         result.setColumnNames(SpanConfig.getGuiFieldsNames());
626         result.setNodeData(spanConfigs);
627         return result;
628     }
629
630     @RequestMapping(value = "/nodeports")
631     @ResponseBody
632     public Map<String, Object> getNodePorts(HttpServletRequest request,
633             @RequestParam(required = false) String container) {
634         String containerName = (container == null) ? GlobalConstants.DEFAULT
635                 .toString() : container;
636
637         // Derive the privilege this user has on the current container
638         String userName = request.getUserPrincipal().getName();
639         if (DaylightWebUtil.getContainerPrivilege(userName, containerName, this) == Privilege.NONE) {
640             return null;
641         }
642
643
644         ISwitchManager switchManager = (ISwitchManager) ServiceHelper
645                 .getInstance(ISwitchManager.class, containerName, this);
646         if (switchManager == null) {
647             return null;
648         }
649
650         Map<String, Object> nodes = new HashMap<String, Object>();
651         Map<Short, String> port;
652
653         for (Switch node : switchManager.getNetworkDevices()) {
654             port = new HashMap<Short, String>(); // new port
655             Set<NodeConnector> nodeConnectorSet = node.getNodeConnectors();
656
657             if (nodeConnectorSet != null) {
658                 for (NodeConnector nodeConnector : nodeConnectorSet) {
659                     String nodeConnectorName = ((Name) switchManager
660                             .getNodeConnectorProp(nodeConnector,
661                                     Name.NamePropName)).getValue();
662                     port.put((Short) nodeConnector.getID(), nodeConnectorName
663                             + "(" + nodeConnector.getID() + ")");
664                 }
665             }
666
667             nodes.put(node.getNode().toString(), port);
668         }
669
670         return nodes;
671     }
672
673     @RequestMapping(value = "/spanPorts/add", method = RequestMethod.GET)
674     @ResponseBody
675     public StatusJsonBean addSpanPort(
676             @RequestParam("jsonData") String jsonData,
677             HttpServletRequest request,
678             @RequestParam(required = false) String container) {
679         String containerName = (container == null) ? GlobalConstants.DEFAULT
680                 .toString() : container;
681
682         // Authorization check
683         String userName = request.getUserPrincipal().getName();
684         if (DaylightWebUtil.getContainerPrivilege(userName, containerName, this) != Privilege.WRITE) {
685             return unauthorizedMessage();
686         }
687
688         StatusJsonBean resultBean = new StatusJsonBean();
689         try {
690             Gson gson = new Gson();
691             ISwitchManager switchManager = (ISwitchManager) ServiceHelper
692                     .getInstance(ISwitchManager.class, containerName, this);
693             SpanConfig cfgObject = gson.fromJson(jsonData, SpanConfig.class);
694             Status result = switchManager.addSpanConfig(cfgObject);
695             if (result.isSuccess()) {
696                 resultBean.setStatus(true);
697                 resultBean.setMessage("SPAN Port added successfully");
698             } else {
699                 resultBean.setStatus(false);
700                 resultBean.setMessage(result.getDescription());
701             }
702         } catch (Exception e) {
703             resultBean.setStatus(false);
704             resultBean.setMessage("Error occurred while adding span port. "
705                     + e.getMessage());
706         }
707         return resultBean;
708     }
709
710     @RequestMapping(value = "/spanPorts/delete", method = RequestMethod.GET)
711     @ResponseBody
712     public StatusJsonBean deleteSpanPorts(
713             @RequestParam("spanPortsToDelete") String spanPortsToDelete,
714             HttpServletRequest request,
715             @RequestParam(required = false) String container) {
716         String containerName = (container == null) ? GlobalConstants.DEFAULT
717                 .toString() : container;
718
719         // Authorization check
720         String userName = request.getUserPrincipal().getName();
721         if (DaylightWebUtil.getContainerPrivilege(userName, containerName, this) != Privilege.WRITE) {
722             return unauthorizedMessage();
723         }
724
725         StatusJsonBean resultBean = new StatusJsonBean();
726         try {
727             Gson gson = new Gson();
728             ISwitchManager switchManager = (ISwitchManager) ServiceHelper
729                     .getInstance(ISwitchManager.class, containerName, this);
730             String[] spans = spanPortsToDelete.split("###");
731             resultBean.setStatus(true);
732             resultBean.setMessage("SPAN Port(s) deleted successfully");
733             for (String span : spans) {
734                 if (!span.isEmpty()) {
735                     SpanConfig cfgObject = gson
736                             .fromJson(span, SpanConfig.class);
737                     Status result = switchManager.removeSpanConfig(cfgObject);
738                     if (!result.isSuccess()) {
739                         resultBean.setStatus(false);
740                         resultBean.setMessage(result.getDescription());
741                         break;
742                     }
743                 }
744             }
745         } catch (Exception e) {
746             resultBean.setStatus(false);
747             resultBean.setMessage("Error occurred while deleting span port. "
748                     + e.getMessage());
749         }
750         return resultBean;
751     }
752
753     private String getNodeDesc(String nodeId, String containerName) {
754         ISwitchManager switchManager = (ISwitchManager) ServiceHelper
755                 .getInstance(ISwitchManager.class, containerName, this);
756         String description = "";
757         if (switchManager != null) {
758             Description desc = (Description) switchManager.getNodeProp(Node.fromString(nodeId), Description.propertyName);
759             if(desc != null) {
760                 description = desc.getValue();
761             }
762         }
763         return (description.isEmpty() || description.equalsIgnoreCase("none")) ? nodeId
764                 : description;
765     }
766
767     private StatusJsonBean unauthorizedMessage() {
768         StatusJsonBean message = new StatusJsonBean();
769         message.setStatus(false);
770         message.setMessage("Operation not authorized");
771         return message;
772     }
773
774     @RequestMapping(value = "login")
775     public String login(final HttpServletRequest request,
776             final HttpServletResponse response) {
777         // response.setHeader("X-Page-Location", "/login");
778         /*
779          * IUserManager userManager = (IUserManager) ServiceHelper
780          * .getGlobalInstance(IUserManager.class, this); if (userManager ==
781          * null) { return "User Manager is not available"; }
782          *
783          * String username = request.getUserPrincipal().getName();
784          *
785          *
786          * model.addAttribute("username", username); model.addAttribute("role",
787          * userManager.getUserLevel(username).toNumber());
788          */
789         return "forward:" + "/";
790     }
791
792 }