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