Fixing a minor bug in Cache replace code in Connection Manager.
[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                 DaylightWebUtil.auditlog("Node", userName, "updated", nodeId + " to "+ nodeName, containerName);
260             }
261         } catch (Exception e) {
262             resultBean.setStatus(false);
263             resultBean.setMessage("Error updating node information. "
264                     + e.getMessage());
265         }
266         return resultBean;
267     }
268
269     @RequestMapping(value = "/staticRoutes", method = RequestMethod.GET)
270     @ResponseBody
271     public DevicesJsonBean getStaticRoutes(HttpServletRequest request,
272             @RequestParam(required = false) String container) {
273         Gson gson = new Gson();
274         String containerName = (container == null) ? GlobalConstants.DEFAULT
275                 .toString() : container;
276
277         // Derive the privilege this user has on the current container
278         String userName = request.getUserPrincipal().getName();
279         Privilege privilege = DaylightWebUtil.getContainerPrivilege(userName, containerName, this);
280
281         IForwardingStaticRouting staticRouting = (IForwardingStaticRouting) ServiceHelper
282                 .getInstance(IForwardingStaticRouting.class, containerName,
283                         this);
284         if (staticRouting == null) {
285             return null;
286         }
287         List<Map<String, String>> staticRoutes = new ArrayList<Map<String, String>>();
288         ConcurrentMap<String, StaticRouteConfig> routeConfigs = staticRouting
289                 .getStaticRouteConfigs();
290         if (routeConfigs == null) {
291             return null;
292         }
293         if (privilege != Privilege.NONE) {
294             for (StaticRouteConfig conf : routeConfigs.values()) {
295                 Map<String, String> staticRoute = new HashMap<String, String>();
296                 staticRoute.put("name", conf.getName());
297                 staticRoute.put("staticRoute", conf.getStaticRoute());
298                 staticRoute.put("nextHopType", conf.getNextHopType());
299                 staticRoute.put("nextHop", conf.getNextHop());
300                 staticRoute.put("json", gson.toJson(conf));
301                 staticRoutes.add(staticRoute);
302             }
303         }
304         DevicesJsonBean result = new DevicesJsonBean();
305         result.setPrivilege(privilege);
306         result.setColumnNames(StaticRouteConfig.getGuiFieldsNames());
307         result.setNodeData(staticRoutes);
308         return result;
309     }
310
311     @RequestMapping(value = "/staticRoute/add", method = RequestMethod.GET)
312     @ResponseBody
313     public StatusJsonBean addStaticRoute(
314             @RequestParam("routeName") String routeName,
315             @RequestParam("staticRoute") String staticRoute,
316             @RequestParam("nextHop") String nextHop,
317             HttpServletRequest request,
318             @RequestParam(required = false) String container) {
319         String containerName = (container == null) ? GlobalConstants.DEFAULT
320                 .toString() : container;
321
322         // Authorization check
323         String userName = request.getUserPrincipal().getName();
324         if (DaylightWebUtil
325                 .getContainerPrivilege(userName, containerName, this) != Privilege.WRITE) {
326             return unauthorizedMessage();
327         }
328
329         StatusJsonBean result = new StatusJsonBean();
330         try {
331             IForwardingStaticRouting staticRouting = (IForwardingStaticRouting) ServiceHelper
332                     .getInstance(IForwardingStaticRouting.class, containerName,
333                             this);
334             StaticRouteConfig config = new StaticRouteConfig();
335             config.setName(routeName);
336             config.setStaticRoute(staticRoute);
337             config.setNextHop(nextHop);
338             Status addStaticRouteResult = staticRouting.addStaticRoute(config);
339             if (addStaticRouteResult.isSuccess()) {
340                 result.setStatus(true);
341                 result.setMessage("Static Route saved successfully");
342                 DaylightWebUtil.auditlog("Static Route", userName, "added", routeName, containerName);
343             } else {
344                 result.setStatus(false);
345                 result.setMessage(addStaticRouteResult.getDescription());
346             }
347         } catch (Exception e) {
348             result.setStatus(false);
349             result.setMessage("Error - " + e.getMessage());
350         }
351         return result;
352     }
353
354     @RequestMapping(value = "/staticRoute/delete", method = RequestMethod.GET)
355     @ResponseBody
356     public StatusJsonBean deleteStaticRoute(
357             @RequestParam("routesToDelete") String routesToDelete,
358             HttpServletRequest request,
359             @RequestParam(required = false) String container) {
360         String containerName = (container == null) ? GlobalConstants.DEFAULT
361                 .toString() : container;
362
363         // Authorization check
364         String userName = request.getUserPrincipal().getName();
365         if (DaylightWebUtil.getContainerPrivilege(userName, containerName, this) != Privilege.WRITE) {
366             return unauthorizedMessage();
367         }
368
369         StatusJsonBean resultBean = new StatusJsonBean();
370         try {
371             IForwardingStaticRouting staticRouting = (IForwardingStaticRouting) ServiceHelper
372                     .getInstance(IForwardingStaticRouting.class, containerName,
373                             this);
374             String[] routes = routesToDelete.split(",");
375             Status result;
376             resultBean.setStatus(true);
377             resultBean
378                     .setMessage("Successfully deleted selected static routes");
379             for (String route : routes) {
380                 result = staticRouting.removeStaticRoute(route);
381                 if (!result.isSuccess()) {
382                     resultBean.setStatus(false);
383                     resultBean.setMessage(result.getDescription());
384                     break;
385                 }
386                 DaylightWebUtil.auditlog("Static Route", userName, "removed", route, containerName);
387             }
388         } catch (Exception e) {
389             resultBean.setStatus(false);
390             resultBean
391                     .setMessage("Error occurred while deleting static routes. "
392                             + e.getMessage());
393         }
394         return resultBean;
395     }
396
397     @RequestMapping(value = "/subnets", method = RequestMethod.GET)
398     @ResponseBody
399     public DevicesJsonBean getSubnetGateways(HttpServletRequest request,
400             @RequestParam(required = false) String container) {
401         Gson gson = new Gson();
402         List<Map<String, String>> subnets = new ArrayList<Map<String, String>>();
403         String containerName = (container == null) ? GlobalConstants.DEFAULT
404                 .toString() : container;
405
406         // Derive the privilege this user has on the current container
407         String userName = request.getUserPrincipal().getName();
408         Privilege privilege = DaylightWebUtil.getContainerPrivilege(
409                 userName, containerName, this);
410
411         if (privilege != Privilege.NONE) {
412             ISwitchManager switchManager = (ISwitchManager) ServiceHelper
413                     .getInstance(ISwitchManager.class, containerName, this);
414             if (switchManager != null) {
415                 for (SubnetConfig conf : switchManager.getSubnetsConfigList()) {
416                     Map<String, String> subnet = new HashMap<String, String>();
417                     subnet.put("name", conf.getName());
418                     subnet.put("subnet", conf.getSubnet());
419                     subnet.put("json", gson.toJson(conf));
420                     subnets.add(subnet);
421                 }
422             }
423         }
424         DevicesJsonBean result = new DevicesJsonBean();
425         result.setPrivilege(privilege);
426         result.setColumnNames(SubnetConfig.getGuiFieldsNames());
427         result.setNodeData(subnets);
428         return result;
429     }
430
431     @RequestMapping(value = "/subnetGateway/add", method = RequestMethod.GET)
432     @ResponseBody
433     public StatusJsonBean addSubnetGateways(
434             @RequestParam("gatewayName") String gatewayName,
435             @RequestParam("gatewayIPAddress") String gatewayIPAddress,
436             HttpServletRequest request,
437             @RequestParam(required = false) String container) {
438         String containerName = (container == null) ? GlobalConstants.DEFAULT
439                 .toString() : container;
440
441         // Authorization check
442         String userName = request.getUserPrincipal().getName();
443         if (DaylightWebUtil.getContainerPrivilege(userName, containerName, this) != Privilege.WRITE) {
444             return unauthorizedMessage();
445         }
446
447         StatusJsonBean resultBean = new StatusJsonBean();
448         try {
449             ISwitchManager switchManager = (ISwitchManager) ServiceHelper
450                     .getInstance(ISwitchManager.class, containerName, this);
451             SubnetConfig cfgObject = new SubnetConfig(gatewayName,
452                     gatewayIPAddress, new HashSet<String>());
453             Status result = switchManager.addSubnet(cfgObject);
454             if (result.isSuccess()) {
455                 resultBean.setStatus(true);
456                 resultBean.setMessage("Added gateway address successfully");
457                 DaylightWebUtil.auditlog("Subnet Gateway", userName, "added", gatewayName, containerName);
458             } else {
459                 resultBean.setStatus(false);
460                 resultBean.setMessage(result.getDescription());
461             }
462         } catch (Exception e) {
463             resultBean.setStatus(false);
464             resultBean.setMessage(e.getMessage());
465         }
466         return resultBean;
467     }
468
469     @RequestMapping(value = "/subnetGateway/delete", method = RequestMethod.GET)
470     @ResponseBody
471     public StatusJsonBean deleteSubnetGateways(
472             @RequestParam("gatewaysToDelete") String gatewaysToDelete,
473             HttpServletRequest request,
474             @RequestParam(required = false) String container) {
475         String containerName = (container == null) ? GlobalConstants.DEFAULT
476                 .toString() : container;
477
478         // Authorization check
479         String userName = request.getUserPrincipal().getName();
480         if (DaylightWebUtil.getContainerPrivilege(userName, container, this) != Privilege.WRITE) {
481             return unauthorizedMessage();
482         }
483
484         StatusJsonBean resultBean = new StatusJsonBean();
485         try {
486             ISwitchManager switchManager = (ISwitchManager) ServiceHelper
487                     .getInstance(ISwitchManager.class, containerName, this);
488             String[] subnets = gatewaysToDelete.split(",");
489             resultBean.setStatus(true);
490             resultBean.setMessage("Added gateway address successfully");
491             for (String subnet : subnets) {
492                 Status result = switchManager.removeSubnet(subnet);
493                 if (!result.isSuccess()) {
494                     resultBean.setStatus(false);
495                     resultBean.setMessage(result.getDescription());
496                     break;
497                 }
498                 DaylightWebUtil.auditlog("Subnet Gateway", userName, "removed", subnet, containerName);
499             }
500         } catch (Exception e) {
501             resultBean.setStatus(false);
502             resultBean.setMessage(e.getMessage());
503         }
504         return resultBean;
505     }
506
507     @RequestMapping(value = "/subnetGateway/ports/add", method = RequestMethod.GET)
508     @ResponseBody
509     public StatusJsonBean addSubnetGatewayPort(
510             @RequestParam("portsName") String portsName,
511             @RequestParam("ports") String ports,
512             @RequestParam("nodeId") String nodeId, HttpServletRequest request,
513             @RequestParam(required = false) String container) {
514         String containerName = (container == null) ? GlobalConstants.DEFAULT
515                 .toString() : container;
516
517         // Authorization check
518         String userName = request.getUserPrincipal().getName();
519         if (DaylightWebUtil.getContainerPrivilege(userName, containerName, this) != Privilege.WRITE) {
520             return unauthorizedMessage();
521         }
522
523         StatusJsonBean resultBean = new StatusJsonBean();
524         try {
525             ISwitchManager switchManager = (ISwitchManager) ServiceHelper
526                     .getInstance(ISwitchManager.class, containerName, this);
527             Status result = switchManager.addPortsToSubnet(portsName, nodeId
528                     + "/" + ports);
529
530             if (result.isSuccess()) {
531                 resultBean.setStatus(true);
532                 resultBean
533                         .setMessage("Added ports to subnet gateway address successfully");
534                 DaylightWebUtil.auditlog("Ports to Subnet Gateway", userName, "added",nodeId+"/"+ ports, containerName);
535             } else {
536                 resultBean.setStatus(false);
537                 resultBean.setMessage(result.getDescription());
538             }
539         } catch (Exception e) {
540             resultBean.setStatus(false);
541             resultBean.setMessage(e.getMessage());
542         }
543         return resultBean;
544     }
545
546     @RequestMapping(value = "/subnetGateway/ports/delete", method = RequestMethod.GET)
547     @ResponseBody
548     public StatusJsonBean deleteSubnetGatewayPort(
549             @RequestParam("gatewayName") String gatewayName,
550             @RequestParam("nodePort") String nodePort,
551             HttpServletRequest request,
552             @RequestParam(required = false) String container) {
553         String containerName = (container == null) ? GlobalConstants.DEFAULT
554                 .toString() : container;
555
556         // Authorization check
557         String userName = request.getUserPrincipal().getName();
558         if (DaylightWebUtil.getContainerPrivilege(userName, containerName, this) != Privilege.WRITE) {
559             return unauthorizedMessage();
560         }
561
562         StatusJsonBean resultBean = new StatusJsonBean();
563         try {
564             ISwitchManager switchManager = (ISwitchManager) ServiceHelper
565                     .getInstance(ISwitchManager.class, containerName, this);
566             Status result = switchManager.removePortsFromSubnet(gatewayName,
567                     nodePort);
568
569             if (result.isSuccess()) {
570                 resultBean.setStatus(true);
571                 resultBean
572                         .setMessage("Deleted port from subnet gateway address successfully");
573                 DaylightWebUtil.auditlog("Ports from Subnet Gateway", userName, "removed", nodePort, containerName);
574             } else {
575                 resultBean.setStatus(false);
576                 resultBean.setMessage(result.getDescription());
577             }
578         } catch (Exception e) {
579             resultBean.setStatus(false);
580             resultBean.setMessage(e.getMessage());
581         }
582         return resultBean;
583     }
584
585     @RequestMapping(value = "/spanPorts", method = RequestMethod.GET)
586     @ResponseBody
587     public DevicesJsonBean getSpanPorts(HttpServletRequest request,
588             @RequestParam(required = false) String container) {
589         Gson gson = new Gson();
590         List<Map<String, String>> spanConfigs = new ArrayList<Map<String, String>>();
591         String containerName = (container == null) ? GlobalConstants.DEFAULT
592                 .toString() : container;
593
594         // Derive the privilege this user has on the current container
595         String userName = request.getUserPrincipal().getName();
596         Privilege privilege = DaylightWebUtil.getContainerPrivilege(
597                 userName, containerName, this);
598
599         if (privilege != Privilege.NONE) {
600             List<String> spanConfigs_json = new ArrayList<String>();
601             ISwitchManager switchManager = (ISwitchManager) ServiceHelper
602                     .getInstance(ISwitchManager.class, containerName, this);
603             if (switchManager != null) {
604                 for (SpanConfig conf : switchManager.getSpanConfigList()) {
605                     spanConfigs_json.add(gson.toJson(conf));
606                 }
607             }
608             ObjectMapper mapper = new ObjectMapper();
609
610             for (String config_json : spanConfigs_json) {
611                 try {
612                     @SuppressWarnings("unchecked")
613                     Map<String, String> config_data = mapper.readValue(config_json,
614                             HashMap.class);
615                     Map<String, String> config = new HashMap<String, String>();
616                     for (String name : config_data.keySet()) {
617                         config.put(name, config_data.get(name));
618                         // Add switch name value (non-configuration field)
619                         config.put("nodeName",
620                                 getNodeDesc(config_data.get("nodeId"), containerName));
621                     }
622                     config.put("json", config_json);
623                     spanConfigs.add(config);
624                 } catch (Exception e) {
625                     // TODO: Handle the exception.
626                 }
627             }
628         }
629
630         DevicesJsonBean result = new DevicesJsonBean();
631         result.setPrivilege(privilege);
632         result.setColumnNames(SpanConfig.getGuiFieldsNames());
633         result.setNodeData(spanConfigs);
634         return result;
635     }
636
637     @RequestMapping(value = "/nodeports")
638     @ResponseBody
639     public Map<String, Object> getNodePorts(HttpServletRequest request,
640             @RequestParam(required = false) String container) {
641         String containerName = (container == null) ? GlobalConstants.DEFAULT
642                 .toString() : container;
643
644         // Derive the privilege this user has on the current container
645         String userName = request.getUserPrincipal().getName();
646         if (DaylightWebUtil.getContainerPrivilege(userName, containerName, this) == Privilege.NONE) {
647             return null;
648         }
649
650
651         ISwitchManager switchManager = (ISwitchManager) ServiceHelper
652                 .getInstance(ISwitchManager.class, containerName, this);
653         if (switchManager == null) {
654             return null;
655         }
656
657         Map<String, Object> nodes = new HashMap<String, Object>();
658         Map<Short, String> port;
659
660         for (Switch node : switchManager.getNetworkDevices()) {
661             port = new HashMap<Short, String>(); // new port
662             Set<NodeConnector> nodeConnectorSet = node.getNodeConnectors();
663
664             if (nodeConnectorSet != null) {
665                 for (NodeConnector nodeConnector : nodeConnectorSet) {
666                     String nodeConnectorName = ((Name) switchManager
667                             .getNodeConnectorProp(nodeConnector,
668                                     Name.NamePropName)).getValue();
669                     port.put((Short) nodeConnector.getID(), nodeConnectorName
670                             + "(" + nodeConnector.getID() + ")");
671                 }
672             }
673
674             nodes.put(node.getNode().toString(), port);
675         }
676
677         return nodes;
678     }
679
680     @RequestMapping(value = "/spanPorts/add", method = RequestMethod.GET)
681     @ResponseBody
682     public StatusJsonBean addSpanPort(
683             @RequestParam("jsonData") String jsonData,
684             HttpServletRequest request,
685             @RequestParam(required = false) String container) {
686         String containerName = (container == null) ? GlobalConstants.DEFAULT
687                 .toString() : container;
688
689         // Authorization check
690         String userName = request.getUserPrincipal().getName();
691         if (DaylightWebUtil.getContainerPrivilege(userName, containerName, this) != Privilege.WRITE) {
692             return unauthorizedMessage();
693         }
694
695         StatusJsonBean resultBean = new StatusJsonBean();
696         try {
697             Gson gson = new Gson();
698             ISwitchManager switchManager = (ISwitchManager) ServiceHelper
699                     .getInstance(ISwitchManager.class, containerName, this);
700             SpanConfig cfgObject = gson.fromJson(jsonData, SpanConfig.class);
701             Status result = switchManager.addSpanConfig(cfgObject);
702             if (result.isSuccess()) {
703                 resultBean.setStatus(true);
704                 resultBean.setMessage("SPAN Port added successfully");
705                 DaylightWebUtil.auditlog("SPAN Port", userName, "added", cfgObject.getNodeId(), containerName);
706             } else {
707                 resultBean.setStatus(false);
708                 resultBean.setMessage(result.getDescription());
709             }
710         } catch (Exception e) {
711             resultBean.setStatus(false);
712             resultBean.setMessage("Error occurred while adding span port. "
713                     + e.getMessage());
714         }
715         return resultBean;
716     }
717
718     @RequestMapping(value = "/spanPorts/delete", method = RequestMethod.GET)
719     @ResponseBody
720     public StatusJsonBean deleteSpanPorts(
721             @RequestParam("spanPortsToDelete") String spanPortsToDelete,
722             HttpServletRequest request,
723             @RequestParam(required = false) String container) {
724         String containerName = (container == null) ? GlobalConstants.DEFAULT
725                 .toString() : container;
726
727         // Authorization check
728         String userName = request.getUserPrincipal().getName();
729         if (DaylightWebUtil.getContainerPrivilege(userName, containerName, this) != Privilege.WRITE) {
730             return unauthorizedMessage();
731         }
732
733         StatusJsonBean resultBean = new StatusJsonBean();
734         try {
735             Gson gson = new Gson();
736             ISwitchManager switchManager = (ISwitchManager) ServiceHelper
737                     .getInstance(ISwitchManager.class, containerName, this);
738             String[] spans = spanPortsToDelete.split("###");
739             resultBean.setStatus(true);
740             resultBean.setMessage("SPAN Port(s) deleted successfully");
741             for (String span : spans) {
742                 if (!span.isEmpty()) {
743                     SpanConfig cfgObject = gson
744                             .fromJson(span, SpanConfig.class);
745                     Status result = switchManager.removeSpanConfig(cfgObject);
746                     if (!result.isSuccess()) {
747                         resultBean.setStatus(false);
748                         resultBean.setMessage(result.getDescription());
749                         break;
750                     }
751                     DaylightWebUtil.auditlog("SPAN Port", userName, "removed", cfgObject.getNodeId(), containerName);
752                 }
753             }
754         } catch (Exception e) {
755             resultBean.setStatus(false);
756             resultBean.setMessage("Error occurred while deleting span port. "
757                     + e.getMessage());
758         }
759         return resultBean;
760     }
761
762     private String getNodeDesc(String nodeId, String containerName) {
763         ISwitchManager switchManager = (ISwitchManager) ServiceHelper
764                 .getInstance(ISwitchManager.class, containerName, this);
765         String description = "";
766         if (switchManager != null) {
767             Description desc = (Description) switchManager.getNodeProp(Node.fromString(nodeId), Description.propertyName);
768             if(desc != null) {
769                 description = desc.getValue();
770             }
771         }
772         return (description.isEmpty() || description.equalsIgnoreCase("none")) ? nodeId
773                 : description;
774     }
775
776     private StatusJsonBean unauthorizedMessage() {
777         StatusJsonBean message = new StatusJsonBean();
778         message.setStatus(false);
779         message.setMessage("Operation not authorized");
780         return message;
781     }
782
783     @RequestMapping(value = "login")
784     public String login(final HttpServletRequest request,
785             final HttpServletResponse response) {
786         // response.setHeader("X-Page-Location", "/login");
787         /*
788          * IUserManager userManager = (IUserManager) ServiceHelper
789          * .getGlobalInstance(IUserManager.class, this); if (userManager ==
790          * null) { return "User Manager is not available"; }
791          *
792          * String username = request.getUserPrincipal().getName();
793          *
794          *
795          * model.addAttribute("username", username); model.addAttribute("role",
796          * userManager.getUserLevel(username).toNumber());
797          */
798         return "forward:" + "/";
799     }
800
801 }