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