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