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