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