Merge "Changed model versions to dependencies"
[controller.git] / opendaylight / northbound / switchmanager / src / main / java / org / opendaylight / controller / switchmanager / northbound / SwitchNorthbound.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.switchmanager.northbound;
10
11 import java.util.ArrayList;
12 import java.util.HashMap;
13 import java.util.HashSet;
14 import java.util.List;
15 import java.util.Map;
16 import java.util.Set;
17
18 import javax.ws.rs.Consumes;
19 import javax.ws.rs.DELETE;
20 import javax.ws.rs.GET;
21 import javax.ws.rs.POST;
22 import javax.ws.rs.PUT;
23 import javax.ws.rs.Path;
24 import javax.ws.rs.PathParam;
25 import javax.ws.rs.Produces;
26 import javax.ws.rs.core.Context;
27 import javax.ws.rs.core.MediaType;
28 import javax.ws.rs.core.Response;
29 import javax.ws.rs.core.SecurityContext;
30 import javax.ws.rs.core.UriInfo;
31
32 import org.codehaus.enunciate.jaxrs.ResponseCode;
33 import org.codehaus.enunciate.jaxrs.StatusCodes;
34 import org.codehaus.enunciate.jaxrs.TypeHint;
35 import org.opendaylight.controller.containermanager.IContainerManager;
36 import org.opendaylight.controller.northbound.commons.RestMessages;
37 import org.opendaylight.controller.northbound.commons.exception.InternalServerErrorException;
38 import org.opendaylight.controller.northbound.commons.exception.ResourceNotFoundException;
39 import org.opendaylight.controller.northbound.commons.exception.ServiceUnavailableException;
40 import org.opendaylight.controller.northbound.commons.exception.UnauthorizedException;
41 import org.opendaylight.controller.northbound.commons.utils.NorthboundUtils;
42 import org.opendaylight.controller.sal.authorization.Privilege;
43 import org.opendaylight.controller.sal.core.Node;
44 import org.opendaylight.controller.sal.core.NodeConnector;
45 import org.opendaylight.controller.sal.core.Property;
46 import org.opendaylight.controller.sal.utils.GlobalConstants;
47 import org.opendaylight.controller.sal.utils.ServiceHelper;
48 import org.opendaylight.controller.sal.utils.Status;
49 import org.opendaylight.controller.sal.utils.StatusCode;
50 import org.opendaylight.controller.switchmanager.ISwitchManager;
51 import org.opendaylight.controller.switchmanager.SwitchConfig;
52
53 /**
54  * The class provides Northbound REST APIs to access the nodes, node connectors
55  * and their properties.
56  *
57  */
58
59 @Path("/")
60 public class SwitchNorthbound {
61
62     private String username;
63
64     @Context
65     public void setSecurityContext(SecurityContext context) {
66         if (context != null && context.getUserPrincipal() != null) {
67             username = context.getUserPrincipal().getName();
68         }
69     }
70
71     protected String getUserName() {
72         return username;
73     }
74
75     private ISwitchManager getIfSwitchManagerService(String containerName) {
76         IContainerManager containerManager = (IContainerManager) ServiceHelper.getGlobalInstance(
77                 IContainerManager.class, this);
78         if (containerManager == null) {
79             throw new ServiceUnavailableException("Container " + RestMessages.SERVICEUNAVAILABLE.toString());
80         }
81
82         boolean found = false;
83         List<String> containerNames = containerManager.getContainerNames();
84         for (String cName : containerNames) {
85             if (cName.trim().equalsIgnoreCase(containerName.trim())) {
86                 found = true;
87                 break;
88             }
89         }
90
91         if (found == false) {
92             throw new ResourceNotFoundException(containerName + " " + RestMessages.NOCONTAINER.toString());
93         }
94
95         ISwitchManager switchManager = (ISwitchManager) ServiceHelper.getInstance(ISwitchManager.class, containerName,
96                 this);
97
98         if (switchManager == null) {
99             throw new ServiceUnavailableException("Switch Manager " + RestMessages.SERVICEUNAVAILABLE.toString());
100         }
101
102         return switchManager;
103     }
104
105     /**
106      *
107      * Retrieve a list of all the nodes and their properties in the network
108      *
109      * @param containerName
110      *            Name of the Container (Eg. 'default')
111      * @return A list of Pair each pair represents a
112      *         {@link org.opendaylight.controller.sal.core.Node} and Set of
113      *         {@link org.opendaylight.controller.sal.core.Property} attached to
114      *         it.
115      *
116      *         <pre>
117      *
118      * Example:
119      *
120      * Request URL:
121      * http://localhost:8080/controller/nb/v2/switchmanager/default/nodes
122      *
123      * Response body in XML:
124      * &lt;?xml version="1.0" encoding="UTF-8" standalone="yes"?&gt;
125      * &lt;list&gt;
126      *     &#x20;&#x20;&#x20;&lt;nodeProperties&gt;
127      *         &#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&lt;node&gt;
128      *             &#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&lt;id&gt;00:00:00:00:00:00:00:02&lt;/id&gt;
129      *             &#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&lt;type&gt;OF&lt;/type&gt;
130      *         &#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&lt;/node&gt;
131      *         &#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&lt;properties&gt;
132      *             &#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&lt;tables&gt;
133      *                 &#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&lt;value&gt;-1&lt;/value&gt;
134      *             &#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&lt;/tables&gt;
135      *             &#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&lt;description&gt;
136      *                 &#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&lt;value&gt;Switch2&lt;/value&gt;
137      *             &#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&lt;/description&gt;
138      *             &#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&lt;actions&gt;
139      *                 &#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&lt;value&gt;4095&lt;/value&gt;
140      *             &#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&lt;/actions&gt;
141      *             &#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&lt;macAddress&gt;
142      *                 &#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&lt;value&gt;00:00:00:00:00:02&lt;/value&gt;
143      *             &#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&lt;/macAddress&gt;
144      *             &#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&lt;capabilities&gt;
145      *                 &#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&lt;value&gt;199&lt;/value&gt;
146      *             &#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&lt;/capabilities&gt;
147      *             &#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&lt;timeStamp&gt;
148      *                 &#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&lt;value&gt;1377291227877&lt;/value&gt;
149      *                 &#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&lt;name&gt;connectedSince&lt;/name&gt;
150      *             &#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&lt;/timeStamp&gt;
151      *             &#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&lt;buffers&gt;
152      *                 &#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&lt;value&gt;256&lt;/value&gt;
153      *             &#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&lt;/buffers&gt;
154      *         &#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&lt;/properties&gt;
155      *     &#x20;&#x20;&#x20;&lt;/nodeProperties&gt;
156      * &lt;/list&gt;
157      *
158      * Response body in JSON:
159      * {
160      *    "nodeProperties":[
161      *       {
162      *          "node":{
163      *             "id":"00:00:00:00:00:00:00:02",
164      *             "type":"OF"
165      *          },
166      *          "properties":{
167      *             "tables":{
168      *                "value":"-1"
169      *             },
170      *             "description":{
171      *                "value":"None"
172      *             },
173      *             "actions":{
174      *                "value":"4095"
175      *             },
176      *             "macAddress":{
177      *                "value":"00:00:00:00:00:02"
178      *             },
179      *             "capabilities":{
180      *                "value":"199"
181      *             },
182      *             "timeStamp":{
183      *                "value":"1377291227877",
184      *                "name":"connectedSince"
185      *             },
186      *             "buffers":{
187      *                "value":"256"
188      *             }
189      *          }
190      *       }
191      *    ]
192      * }
193      *
194      * </pre>
195      */
196     @Path("/{containerName}/nodes")
197     @GET
198     @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
199     @TypeHint(Nodes.class)
200     @StatusCodes({ @ResponseCode(code = 200, condition = "Operation successful"),
201         @ResponseCode(code = 401, condition = "User not authorized to perform this operation"),
202         @ResponseCode(code = 404, condition = "The containerName is not found"),
203         @ResponseCode(code = 503, condition = "One or more of Controller Services are unavailable") })
204     public Nodes getNodes(@PathParam("containerName") String containerName) {
205
206         if (!isValidContainer(containerName)) {
207             throw new ResourceNotFoundException("Container " + containerName + " does not exist.");
208         }
209
210         if (!NorthboundUtils.isAuthorized(getUserName(), containerName, Privilege.READ, this)) {
211             throw new UnauthorizedException("User is not authorized to perform this operation on container "
212                     + containerName);
213         }
214
215         ISwitchManager switchManager = getIfSwitchManagerService(containerName);
216         if (switchManager == null) {
217             throw new ServiceUnavailableException("Switch Manager " + RestMessages.SERVICEUNAVAILABLE.toString());
218         }
219
220         List<NodeProperties> res = new ArrayList<NodeProperties>();
221         Set<Node> nodes = switchManager.getNodes();
222         if (nodes == null) {
223             return new Nodes(res);
224         }
225
226         for (Node node : nodes) {
227             Map<String, Property> propMap = switchManager.getNodeProps(node);
228             if (propMap == null) {
229                 continue;
230             }
231             Set<Property> props = new HashSet<Property>(propMap.values());
232
233             NodeProperties nodeProps = new NodeProperties(node, props);
234             res.add(nodeProps);
235         }
236
237         return new Nodes(res);
238     }
239
240     /**
241      * Add a Description, Tier and Forwarding mode property to a node. This
242      * method returns a non-successful response if a node by that name already
243      * exists.
244      *
245      * @param containerName
246      *            Name of the Container (Eg. 'default')
247      * @param nodeType
248      *            Type of the node being programmed (Eg. 'OF')
249      * @param nodeId
250      *            Node Identifier as specified by
251      *            {@link org.opendaylight.controller.sal.core.Node} (Eg.
252      *            '00:00:00:00:00:00:00:03')
253      * @param propertyName
254      *            Name of the Property. Properties that can be configured are:
255      *            description, forwarding(only for default container) and tier
256      * @param propertyValue
257      *            Value of the Property. Description can be any string (Eg.
258      *            'Node1'), valid values for tier are non negative numbers, and
259      *            valid values for forwarding are 0 for reactive and 1 for
260      *            proactive forwarding.
261      * @return Response as dictated by the HTTP Response Status code
262      *
263      *         <pre>
264      *
265      * Example:
266      *
267      * Request URL:
268      * http://localhost:8080/controller/nb/v2/switchmanager/default/node/OF/00:00:00:00:00:00:00:03/property/description/Switch3
269      *
270      * </pre>
271      */
272
273     @Path("/{containerName}/node/{nodeType}/{nodeId}/property/{propertyName}/{propertyValue}")
274     @PUT
275     @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
276     @TypeHint(Response.class)
277     @StatusCodes({
278         @ResponseCode(code = 201, condition = "Operation successful"),
279         @ResponseCode(code = 400, condition = "The nodeId or configuration is invalid"),
280         @ResponseCode(code = 401, condition = "User not authorized to perform this operation"),
281         @ResponseCode(code = 404, condition = "The Container Name or node or configuration name is not found"),
282         @ResponseCode(code = 406, condition = "The property cannot be configured in non-default container"),
283         @ResponseCode(code = 409, condition = "Unable to update configuration due to cluster conflict or conflicting description property"),
284         @ResponseCode(code = 503, condition = "One or more of Controller services are unavailable") })
285     public Response addNodeProperty(@Context UriInfo uriInfo, @PathParam("containerName") String containerName,
286             @PathParam("nodeType") String nodeType, @PathParam("nodeId") String nodeId,
287             @PathParam("propertyName") String propertyName, @PathParam("propertyValue") String propertyValue) {
288
289         if (!isValidContainer(containerName)) {
290             throw new ResourceNotFoundException("Container " + containerName + " does not exist.");
291         }
292         if (!NorthboundUtils.isAuthorized(getUserName(), containerName, Privilege.WRITE, this)) {
293             throw new UnauthorizedException("User is not authorized to perform this operation on container "
294                     + containerName);
295         }
296         ISwitchManager switchManager = getIfSwitchManagerService(containerName);
297         if (switchManager == null) {
298             throw new ServiceUnavailableException("Switch Manager " + RestMessages.SERVICEUNAVAILABLE.toString());
299         }
300
301         handleNodeAvailability(containerName, nodeType, nodeId);
302         Node node = Node.fromString(nodeType, nodeId);
303         Property prop = switchManager.createProperty(propertyName, propertyValue);
304         if (prop == null) {
305             throw new ResourceNotFoundException("Property with name " + propertyName + " does not exist.");
306         }
307         SwitchConfig switchConfig = switchManager.getSwitchConfig(node.toString());
308         Map<String, Property> nodeProperties = (switchConfig == null) ? new HashMap<String, Property>()
309                 : new HashMap<String, Property>(switchConfig.getNodeProperties());
310         nodeProperties.put(prop.getName(), prop);
311         SwitchConfig newSwitchConfig = new SwitchConfig(node.toString(), nodeProperties);
312         Status status = switchManager.updateNodeConfig(newSwitchConfig);
313         if (status.isSuccess()) {
314             NorthboundUtils.auditlog("Property " + propertyName, username, "updated",
315                     "of Node " + NorthboundUtils.getNodeDesc(node, switchManager), containerName);
316
317             return Response.created(uriInfo.getRequestUri()).build();
318         }
319         return NorthboundUtils.getResponse(status);
320     }
321
322     /**
323      * Delete a property of a node
324      *
325      * @param containerName
326      *            Name of the Container (Eg. 'SliceRed')
327      * @param nodeType
328      *            Type of the node being programmed (Eg. 'OF')
329      * @param nodeId
330      *            Node Identifier as specified by
331      *            {@link org.opendaylight.controller.sal.core.Node} (Eg.
332      *            '00:00:00:00:00:03:01:02')
333      * @param propertyName
334      *            Name of the Property. Properties that can be deleted are
335      *            description, forwarding(only in default container) and tier.
336      * @return Response as dictated by the HTTP Response Status code
337      *
338      *         <pre>
339      *
340      * Example:
341      *
342      * Request URL:
343      * http://localhost:8080/controller/nb/v2/switchmanager/default/node/OF/00:00:00:00:00:00:00:03/property/forwarding
344      *
345      * </pre>
346      */
347
348     @Path("/{containerName}/node/{nodeType}/{nodeId}/property/{propertyName}")
349     @DELETE
350     @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
351     @StatusCodes({ @ResponseCode(code = 204, condition = "Property removed successfully"),
352         @ResponseCode(code = 400, condition = "The nodeId or configuration is invalid"),
353         @ResponseCode(code = 401, condition = "User not authorized to perform this operation"),
354         @ResponseCode(code = 404, condition = "The Container Name or nodeId or configuration name is not found"),
355         @ResponseCode(code = 409, condition = "Unable to delete property due to cluster conflict"),
356         @ResponseCode(code = 503, condition = "One or more of Controller services are unavailable") })
357     public Response deleteNodeProperty(@PathParam("containerName") String containerName,
358             @PathParam("nodeType") String nodeType, @PathParam("nodeId") String nodeId,
359             @PathParam("propertyName") String propertyName) {
360
361         if (!isValidContainer(containerName)) {
362             throw new ResourceNotFoundException("Container " + containerName + " does not exist.");
363         }
364         if (!NorthboundUtils.isAuthorized(getUserName(), containerName, Privilege.WRITE, this)) {
365             throw new UnauthorizedException("User is not authorized to perform this operation on container "
366                     + containerName);
367         }
368         ISwitchManager switchManager = getIfSwitchManagerService(containerName);
369         if (switchManager == null) {
370             throw new ServiceUnavailableException("Switch Manager " + RestMessages.SERVICEUNAVAILABLE.toString());
371         }
372
373         handleNodeAvailability(containerName, nodeType, nodeId);
374         Node node = Node.fromString(nodeType, nodeId);
375
376         SwitchConfig switchConfig = switchManager.getSwitchConfig(node.toString());
377         Status status;
378         if (switchConfig == null) {
379             status = new Status(StatusCode.NOTFOUND, "Switch Configuration does not exist");
380         } else {
381             Map<String, Property> nodeProperties = new HashMap<String, Property>(switchConfig.getNodeProperties());
382             if (!nodeProperties.containsKey(propertyName.toLowerCase())) {
383                 String msg = "Property " + propertyName + " does not exist or not configured for switch " + nodeId;
384                 status = new Status(StatusCode.NOTFOUND, msg);
385             } else {
386                 nodeProperties.remove(propertyName.toLowerCase());
387                 SwitchConfig newSwitchConfig = new SwitchConfig(node.toString(), nodeProperties);
388                 status = switchManager.updateNodeConfig(newSwitchConfig);
389                 if (status.isSuccess()) {
390                     NorthboundUtils.auditlog("Property " + propertyName, username, "removed", "of Node "
391                             + NorthboundUtils.getNodeDesc(node, switchManager), containerName);
392                     return Response.noContent().build();
393                 }
394             }
395         }
396         return NorthboundUtils.getResponse(status);
397     }
398
399     /**
400      *
401      * Retrieve a list of all the nodeconnectors and their properties in a given
402      * node
403      *
404      * @param containerName
405      *            The container for which we want to retrieve the list (Eg.
406      *            'default')
407      * @param nodeType
408      *            Type of the node being programmed (Eg. 'OF')
409      * @param nodeId
410      *            Node Identifier as specified by
411      *            {@link org.opendaylight.controller.sal.core.Node} (Eg.
412      *            '00:00:00:00:00:00:00:03')
413      * @return A List of Pair each pair represents a
414      *         {@link org.opendaylight.controller.sal.core.NodeConnector} and
415      *         its corresponding
416      *         {@link org.opendaylight.controller.sal.core.Property} attached to
417      *         it.
418      *
419      * <pre>
420      *
421      * Example:
422      *
423      * Request URL:
424      * http://localhost:8080/controller/nb/v2/switchmanager/default/node/OF/00:00:00:00:00:00:00:01
425      *
426      * Response body in XML:
427      * &lt;?xml version="1.0" encoding="UTF-8" standalone="yes"?&gt;
428      * &lt;list&gt;
429      *     &#x20;&#x20;&#x20;&lt;nodeConnectorProperties&gt;
430      *         &#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&lt;nodeconnector&gt;
431      *             &#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&lt;node&gt;
432      *                 &#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&lt;id&gt;00:00:00:00:00:00:00:01&lt;/id&gt;
433      *                 &#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&lt;type&gt;OF&lt;/type&gt;
434      *             &#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&lt;/node&gt;
435      *             &#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&lt;id&gt;2&lt;/id&gt;
436      *             &#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&lt;type&gt;OF&lt;/type&gt;
437      *         &#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&lt;/nodeconnector&gt;
438      *         &#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&lt;properties&gt;
439      *             &#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&lt;state&gt;
440      *                 &#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&lt;value&gt;1&lt;/value&gt;
441      *             &#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&lt;/state&gt;
442      *             &#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&lt;config&gt;
443      *                 &#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&lt;value&gt;1&lt;/value&gt;
444      *             &#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&lt;/config&gt;
445      *             &#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&lt;name&gt;
446      *                 &#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&lt;value&gt;L1_2-C2_1&lt;/value&gt;
447      *             &#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&lt;/name&gt;
448      *         &#x20;&#x20;&#x20;&#x20;&#x20;&#x20;&lt;/properties&gt;
449      *     &#x20;&#x20;&#x20;&lt;/nodeConnectorProperties&gt;
450      * &lt;/list&gt;
451      *
452      * Response body in JSON:
453      * {
454      *    "nodeConnectorProperties":[
455      *       {
456      *          "nodeconnector":{
457      *             "node":{
458      *                "id":"00:00:00:00:00:00:00:01",
459      *                "type":"OF"
460      *             },
461      *             "id":"2",
462      *             "type":"OF"
463      *          },
464      *          "properties":{
465      *             "state":{
466      *                "value":"1"
467      *             },
468      *             "config":{
469      *                "value":"1"
470      *             },
471      *             "name":{
472      *                "value":"L1_2-C2_1"
473      *             }
474      *          }
475      *       }
476      *    ]
477      * }
478      *
479      * </pre>
480      */
481     @Path("/{containerName}/node/{nodeType}/{nodeId}")
482     @GET
483     @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
484     @TypeHint(NodeConnectors.class)
485     @StatusCodes({ @ResponseCode(code = 200, condition = "Operation successful"),
486         @ResponseCode(code = 401, condition = "User not authorized to perform this operation"),
487         @ResponseCode(code = 404, condition = "The containerName is not found"),
488         @ResponseCode(code = 503, condition = "One or more of Controller Services are unavailable") })
489     public NodeConnectors getNodeConnectors(@PathParam("containerName") String containerName,
490             @PathParam("nodeType") String nodeType, @PathParam("nodeId") String nodeId) {
491
492         if (!isValidContainer(containerName)) {
493             throw new ResourceNotFoundException("Container " + containerName + " does not exist.");
494         }
495         if (!NorthboundUtils.isAuthorized(getUserName(), containerName, Privilege.READ, this)) {
496             throw new UnauthorizedException("User is not authorized to perform this operation on container "
497                     + containerName);
498         }
499
500         ISwitchManager switchManager = getIfSwitchManagerService(containerName);
501         if (switchManager == null) {
502             throw new ServiceUnavailableException("Switch Manager " + RestMessages.SERVICEUNAVAILABLE.toString());
503         }
504
505         handleNodeAvailability(containerName, nodeType, nodeId);
506         Node node = Node.fromString(nodeType, nodeId);
507         List<NodeConnectorProperties> res = new ArrayList<NodeConnectorProperties>();
508         Set<NodeConnector> ncs = switchManager.getNodeConnectors(node);
509         if (ncs == null) {
510             return null;
511         }
512
513         for (NodeConnector nc : ncs) {
514             Map<String, Property> propMap = switchManager.getNodeConnectorProps(nc);
515             if (propMap == null) {
516                 continue;
517             }
518             Set<Property> props = new HashSet<Property>(propMap.values());
519             NodeConnectorProperties ncProps = new NodeConnectorProperties(nc, props);
520             res.add(ncProps);
521         }
522
523         return new NodeConnectors(res);
524     }
525
526     /**
527      * Add node-connector property to a node connector. This method returns a
528      * non-successful response if a node connector by the given name already
529      * exists.
530      *
531      * @param containerName
532      *            Name of the Container (Eg. 'default')
533      * @param nodeType
534      *            Type of the node being programmed (Eg. 'OF')
535      * @param nodeId
536      *            Node Identifier as specified by
537      *            {@link org.opendaylight.controller.sal.core.Node} (Eg.
538      *            '00:00:00:00:00:00:00:03')
539      * @param nodeConnectorType
540      *            Type of the node connector being programmed (Eg. 'OF')
541      * @param nodeConnectorId
542      *            NodeConnector Identifier as specified by
543      *            {@link org.opendaylight.controller.sal.core.NodeConnector}.
544      *            (Eg. '2'). If nodeConnecterId contains forward slash(/),
545      *            replace forward slash with underscore(_) in the URL. (Eg. for
546      *            Ethernet1/2, use Ethernet1_2)
547      * @param propertyName
548      *            Name of the Property specified by
549      *            {@link org.opendaylight.controller.sal.core.Property} and its
550      *            extended classes Property that can be configured is bandwidth
551      * @param propertyValue
552      *            Value of the Property specified by
553      *            {@link org.opendaylight.controller.sal.core.Property} and its
554      *            extended classes
555      * @return Response as dictated by the HTTP Response Status code
556      *
557      * <pre>
558      *
559      * Example:
560      *
561      * Request URL:
562      * http://localhost:8080/controller/nb/v2/switchmanager/default/nodeconnector/OF/00:00:00:00:00:00:00:01/OF/2/property/bandwidth/1
563      *
564      * </pre>
565      */
566
567     @Path("/{containerName}/nodeconnector/{nodeType}/{nodeId}/{nodeConnectorType}/{nodeConnectorId}/property/{propertyName}/{propertyValue}")
568     @PUT
569     @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
570     @StatusCodes({ @ResponseCode(code = 201, condition = "Operation successful"),
571         @ResponseCode(code = 401, condition = "User not authorized to perform this operation"),
572         @ResponseCode(code = 404, condition = "The Container Name or nodeId or configuration name is not found"),
573         @ResponseCode(code = 409, condition = "Unable to add property due to cluster conflict"),
574         @ResponseCode(code = 503, condition = "One or more of Controller services are unavailable") })
575     public Response addNodeConnectorProperty(@Context UriInfo uriInfo,
576             @PathParam("containerName") String containerName, @PathParam("nodeType") String nodeType,
577             @PathParam("nodeId") String nodeId, @PathParam("nodeConnectorType") String nodeConnectorType,
578             @PathParam("nodeConnectorId") String nodeConnectorId, @PathParam("propertyName") String propertyName,
579             @PathParam("propertyValue") String propertyValue) {
580
581         if (!isValidContainer(containerName)) {
582             throw new ResourceNotFoundException("Container " + containerName + " does not exist.");
583         }
584         if (!NorthboundUtils.isAuthorized(getUserName(), containerName, Privilege.WRITE, this)) {
585             throw new UnauthorizedException("User is not authorized to perform this operation on container "
586                     + containerName);
587         }
588
589         ISwitchManager switchManager = getIfSwitchManagerService(containerName);
590         if (switchManager == null) {
591             throw new ServiceUnavailableException("Switch Manager " + RestMessages.SERVICEUNAVAILABLE.toString());
592         }
593
594         handleNodeAvailability(containerName, nodeType, nodeId);
595         Node node = Node.fromString(nodeType, nodeId);
596
597         if (nodeConnectorId.contains("_")) {
598             nodeConnectorId = nodeConnectorId.replace("_", "/");
599         }
600
601         handleNodeConnectorAvailability(containerName, node, nodeConnectorType, nodeConnectorId);
602         NodeConnector nc = NodeConnector.fromStringNoNode(nodeConnectorType, nodeConnectorId, node);
603
604         Property prop = switchManager.createProperty(propertyName, propertyValue);
605         if (prop == null) {
606             throw new ResourceNotFoundException(RestMessages.INVALIDDATA.toString());
607         }
608
609         Status ret = switchManager.addNodeConnectorProp(nc, prop);
610         if (ret.isSuccess()) {
611             NorthboundUtils.auditlog("Property " + propertyName, username, "updated", "of Node Connector "
612                     + NorthboundUtils.getPortName(nc, switchManager), containerName);
613             return Response.created(uriInfo.getRequestUri()).build();
614         }
615         throw new InternalServerErrorException(ret.getDescription());
616     }
617
618     /**
619      * Delete a property of a node connector
620      *
621      * @param containerName
622      *            Name of the Container (Eg. 'default')
623      * @param nodeType
624      *            Type of the node being programmed (Eg. 'OF')
625      * @param nodeId
626      *            Node Identifier as specified by
627      *            {@link org.opendaylight.controller.sal.core.Node} (Eg.
628      *            '00:00:00:00:00:00:00:01')
629      * @param nodeConnectorType
630      *            Type of the node connector being programmed (Eg. 'OF')
631      * @param nodeConnectorId
632      *            NodeConnector Identifier as specified by
633      *            {@link org.opendaylight.controller.sal.core.NodeConnector}
634      *            (Eg. '1'). If nodeConnecterId contains forward slash(/),
635      *            replace forward slash with underscore(_) in the URL. (Eg. for
636      *            Ethernet1/2, use Ethernet1_2)
637      * @param propertyName
638      *            Name of the Property specified by
639      *            {@link org.opendaylight.controller.sal.core.Property} and its
640      *            extended classes. Property that can be deleted is bandwidth
641      * @return Response as dictated by the HTTP Response Status code
642      *
643      * <pre>
644      *
645      * Example:
646      *
647      * Request URL:
648      * http://localhost:8080/controller/nb/v2/switchmanager/default/nodeconnector/OF/00:00:00:00:00:00:00:01/OF/2/property/bandwidth
649      *
650      * </pre>
651      */
652
653     @Path("/{containerName}/nodeconnector/{nodeType}/{nodeId}/{nodeConnectorType}/{nodeConnectorId}/property/{propertyName}")
654     @DELETE
655     @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
656     @StatusCodes({ @ResponseCode(code = 204, condition = "Property removed successfully"),
657         @ResponseCode(code = 401, condition = "User not authorized to perform this operation"),
658         @ResponseCode(code = 404, condition = "The Container Name or nodeId or configuration name is not found"),
659         @ResponseCode(code = 503, condition = "One or more of Controller services are unavailable") })
660     public Response deleteNodeConnectorProperty(@PathParam("containerName") String containerName,
661             @PathParam("nodeType") String nodeType, @PathParam("nodeId") String nodeId,
662             @PathParam("nodeConnectorType") String nodeConnectorType,
663             @PathParam("nodeConnectorId") String nodeConnectorId, @PathParam("propertyName") String propertyName) {
664
665         if (!isValidContainer(containerName)) {
666             throw new ResourceNotFoundException("Container " + containerName + " does not exist.");
667         }
668         if (!NorthboundUtils.isAuthorized(getUserName(), containerName, Privilege.WRITE, this)) {
669             throw new UnauthorizedException("User is not authorized to perform this operation on container "
670                     + containerName);
671         }
672
673         ISwitchManager switchManager = getIfSwitchManagerService(containerName);
674         if (switchManager == null) {
675             throw new ServiceUnavailableException("Switch Manager " + RestMessages.SERVICEUNAVAILABLE.toString());
676         }
677
678         handleNodeAvailability(containerName, nodeType, nodeId);
679         Node node = Node.fromString(nodeType, nodeId);
680
681         if (nodeConnectorId.contains("_")) {
682             nodeConnectorId = nodeConnectorId.replace("_", "/");
683         }
684
685         handleNodeConnectorAvailability(containerName, node, nodeConnectorType, nodeConnectorId);
686         NodeConnector nc = NodeConnector.fromStringNoNode(nodeConnectorType, nodeConnectorId, node);
687         Status ret = switchManager.removeNodeConnectorProp(nc, propertyName);
688         if (ret.isSuccess()) {
689             NorthboundUtils.auditlog("Property " + propertyName, username, "removed", "of Node Connector "
690                     + NorthboundUtils.getPortName(nc, switchManager), containerName);
691             return Response.noContent().build();
692         }
693         throw new ResourceNotFoundException(ret.getDescription());
694     }
695
696     /**
697      * Save the current switch configurations
698      *
699      * @param containerName
700      *            Name of the Container (Eg. 'default')
701      * @return Response as dictated by the HTTP Response Status code
702      *
703      *         <pre>
704      *
705      * Example:
706      *
707      * Request URL:
708      * http://localhost:8080/controller/nb/v2/switchmanager/default/save
709      *
710      * </pre>
711      */
712     @Path("/{containerName}/save")
713     @POST
714     @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
715     @StatusCodes({
716         @ResponseCode(code = 200, condition = "Operation successful"),
717         @ResponseCode(code = 401, condition = "User not authorized to perform this operation"),
718         @ResponseCode(code = 404, condition = "The containerName is not found"),
719         @ResponseCode(code = 500, condition = "Failed to save switch configuration. Failure Reason included in HTTP Error response"),
720         @ResponseCode(code = 503, condition = "One or more of Controller Services are unavailable") })
721     public Response saveSwitchConfig(@PathParam("containerName") String containerName) {
722
723         if (!isValidContainer(containerName)) {
724             throw new ResourceNotFoundException("Container " + containerName + " does not exist.");
725         }
726         if (!NorthboundUtils.isAuthorized(getUserName(), containerName, Privilege.WRITE, this)) {
727             throw new UnauthorizedException("User is not authorized to perform this operation on container "
728                     + containerName);
729         }
730         ISwitchManager switchManager = getIfSwitchManagerService(containerName);
731         if (switchManager == null) {
732             throw new ServiceUnavailableException("Switch Manager " + RestMessages.SERVICEUNAVAILABLE.toString());
733         }
734
735         Status ret = switchManager.saveSwitchConfig();
736         if (ret.isSuccess()) {
737             return Response.ok().build();
738         }
739         throw new InternalServerErrorException(ret.getDescription());
740     }
741
742     private Node handleNodeAvailability(String containerName, String nodeType, String nodeId) {
743
744         Node node = Node.fromString(nodeType, nodeId);
745         if (node == null) {
746             throw new ResourceNotFoundException(nodeId + " : " + RestMessages.NONODE.toString());
747         }
748
749         ISwitchManager sm = (ISwitchManager) ServiceHelper.getInstance(ISwitchManager.class, containerName, this);
750
751         if (sm == null) {
752             throw new ServiceUnavailableException("Switch Manager " + RestMessages.SERVICEUNAVAILABLE.toString());
753         }
754
755         if (!sm.getNodes().contains(node)) {
756             throw new ResourceNotFoundException(node.toString() + " : " + RestMessages.NONODE.toString());
757         }
758         return node;
759     }
760
761     private void handleNodeConnectorAvailability(String containerName, Node node, String nodeConnectorType,
762             String nodeConnectorId) {
763
764         NodeConnector nc = NodeConnector.fromStringNoNode(nodeConnectorType, nodeConnectorId, node);
765         if (nc == null) {
766             throw new ResourceNotFoundException(nc + " : " + RestMessages.NORESOURCE.toString());
767         }
768
769         ISwitchManager sm = (ISwitchManager) ServiceHelper.getInstance(ISwitchManager.class, containerName, this);
770
771         if (sm == null) {
772             throw new ServiceUnavailableException("Switch Manager " + RestMessages.SERVICEUNAVAILABLE.toString());
773         }
774
775         if (!sm.getNodeConnectors(node).contains(nc)) {
776             throw new ResourceNotFoundException(nc.toString() + " : " + RestMessages.NORESOURCE.toString());
777         }
778     }
779
780     private boolean isValidContainer(String containerName) {
781         if (containerName.equals(GlobalConstants.DEFAULT.toString())) {
782             return true;
783         }
784         IContainerManager containerManager = (IContainerManager) ServiceHelper.getGlobalInstance(
785                 IContainerManager.class, this);
786         if (containerManager == null) {
787             throw new InternalServerErrorException(RestMessages.INTERNALERROR.toString());
788         }
789         if (containerManager.getContainerNames().contains(containerName)) {
790             return true;
791         }
792         return false;
793     }
794
795 }