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')
545      * @param propertyName
546      *            Name of the Property specified by
547      *            {@link org.opendaylight.controller.sal.core.Property} and its
548      *            extended classes Property that can be configured is bandwidth
549      * @param propertyValue
550      *            Value of the Property specified by
551      *            {@link org.opendaylight.controller.sal.core.Property} and its
552      *            extended classes
553      * @return Response as dictated by the HTTP Response Status code
554      *
555      *         <pre>
556      *
557      * Example:
558      *
559      * Request URL:
560      * http://localhost:8080/controller/nb/v2/switchmanager/default/nodeconnector/OF/00:00:00:00:00:00:00:01/OF/2/property/bandwidth/1
561      *
562      * </pre>
563      */
564
565     @Path("/{containerName}/nodeconnector/{nodeType}/{nodeId}/{nodeConnectorType}/{nodeConnectorId}/property/{propertyName}/{propertyValue}")
566     @PUT
567     @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
568     @StatusCodes({ @ResponseCode(code = 201, condition = "Operation successful"),
569         @ResponseCode(code = 401, condition = "User not authorized to perform this operation"),
570         @ResponseCode(code = 404, condition = "The Container Name or nodeId or configuration name is not found"),
571         @ResponseCode(code = 409, condition = "Unable to add property due to cluster conflict"),
572         @ResponseCode(code = 503, condition = "One or more of Controller services are unavailable") })
573     public Response addNodeConnectorProperty(@Context UriInfo uriInfo,
574             @PathParam("containerName") String containerName, @PathParam("nodeType") String nodeType,
575             @PathParam("nodeId") String nodeId, @PathParam("nodeConnectorType") String nodeConnectorType,
576             @PathParam("nodeConnectorId") String nodeConnectorId, @PathParam("propertyName") String propertyName,
577             @PathParam("propertyValue") String propertyValue) {
578
579         if (!isValidContainer(containerName)) {
580             throw new ResourceNotFoundException("Container " + containerName + " does not exist.");
581         }
582         if (!NorthboundUtils.isAuthorized(getUserName(), containerName, Privilege.WRITE, this)) {
583             throw new UnauthorizedException("User is not authorized to perform this operation on container "
584                     + containerName);
585         }
586
587         ISwitchManager switchManager = getIfSwitchManagerService(containerName);
588         if (switchManager == null) {
589             throw new ServiceUnavailableException("Switch Manager " + RestMessages.SERVICEUNAVAILABLE.toString());
590         }
591
592         handleNodeAvailability(containerName, nodeType, nodeId);
593         Node node = Node.fromString(nodeType, nodeId);
594
595         handleNodeConnectorAvailability(containerName, node, nodeConnectorType, nodeConnectorId);
596         NodeConnector nc = NodeConnector.fromStringNoNode(nodeConnectorType, nodeConnectorId, node);
597
598         Property prop = switchManager.createProperty(propertyName, propertyValue);
599         if (prop == null) {
600             throw new ResourceNotFoundException(RestMessages.INVALIDDATA.toString());
601         }
602
603         Status ret = switchManager.addNodeConnectorProp(nc, prop);
604         if (ret.isSuccess()) {
605             NorthboundUtils.auditlog("Property " + propertyName, username, "updated", "of Node Connector "
606                     + NorthboundUtils.getPortName(nc, switchManager), containerName);
607             return Response.created(uriInfo.getRequestUri()).build();
608         }
609         throw new InternalServerErrorException(ret.getDescription());
610     }
611
612     /**
613      * Delete a property of a node connector
614      *
615      * @param containerName
616      *            Name of the Container (Eg. 'default')
617      * @param nodeType
618      *            Type of the node being programmed (Eg. 'OF')
619      * @param nodeId
620      *            Node Identifier as specified by
621      *            {@link org.opendaylight.controller.sal.core.Node} (Eg.
622      *            '00:00:00:00:00:00:00:01')
623      * @param nodeConnectorType
624      *            Type of the node connector being programmed (Eg. 'OF')
625      * @param nodeConnectorId
626      *            NodeConnector Identifier as specified by
627      *            {@link org.opendaylight.controller.sal.core.NodeConnector}
628      *            (Eg. '1')
629      * @param propertyName
630      *            Name of the Property specified by
631      *            {@link org.opendaylight.controller.sal.core.Property} and its
632      *            extended classes. Property that can be deleted is bandwidth
633      * @return Response as dictated by the HTTP Response Status code
634      *
635      *         <pre>
636      *
637      * Example:
638      *
639      * Request URL:
640      * http://localhost:8080/controller/nb/v2/switchmanager/default/nodeconnector/OF/00:00:00:00:00:00:00:01/OF/2/property/bandwidth
641      *
642      * </pre>
643      */
644
645     @Path("/{containerName}/nodeconnector/{nodeType}/{nodeId}/{nodeConnectorType}/{nodeConnectorId}/property/{propertyName}")
646     @DELETE
647     @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
648     @StatusCodes({ @ResponseCode(code = 204, condition = "Property removed successfully"),
649         @ResponseCode(code = 401, condition = "User not authorized to perform this operation"),
650         @ResponseCode(code = 404, condition = "The Container Name or nodeId or configuration name is not found"),
651         @ResponseCode(code = 503, condition = "One or more of Controller services are unavailable") })
652     public Response deleteNodeConnectorProperty(@PathParam("containerName") String containerName,
653             @PathParam("nodeType") String nodeType, @PathParam("nodeId") String nodeId,
654             @PathParam("nodeConnectorType") String nodeConnectorType,
655             @PathParam("nodeConnectorId") String nodeConnectorId, @PathParam("propertyName") String propertyName) {
656
657         if (!isValidContainer(containerName)) {
658             throw new ResourceNotFoundException("Container " + containerName + " does not exist.");
659         }
660         if (!NorthboundUtils.isAuthorized(getUserName(), containerName, Privilege.WRITE, this)) {
661             throw new UnauthorizedException("User is not authorized to perform this operation on container "
662                     + containerName);
663         }
664
665         ISwitchManager switchManager = getIfSwitchManagerService(containerName);
666         if (switchManager == null) {
667             throw new ServiceUnavailableException("Switch Manager " + RestMessages.SERVICEUNAVAILABLE.toString());
668         }
669
670         handleNodeAvailability(containerName, nodeType, nodeId);
671         Node node = Node.fromString(nodeType, nodeId);
672
673         handleNodeConnectorAvailability(containerName, node, nodeConnectorType, nodeConnectorId);
674         NodeConnector nc = NodeConnector.fromStringNoNode(nodeConnectorType, nodeConnectorId, node);
675         Status ret = switchManager.removeNodeConnectorProp(nc, propertyName);
676         if (ret.isSuccess()) {
677             NorthboundUtils.auditlog("Property " + propertyName, username, "removed", "of Node Connector "
678                     + NorthboundUtils.getPortName(nc, switchManager), containerName);
679             return Response.noContent().build();
680         }
681         throw new ResourceNotFoundException(ret.getDescription());
682     }
683
684     /**
685      * Save the current switch configurations
686      *
687      * @param containerName
688      *            Name of the Container (Eg. 'default')
689      * @return Response as dictated by the HTTP Response Status code
690      *
691      *         <pre>
692      *
693      * Example:
694      *
695      * Request URL:
696      * http://localhost:8080/controller/nb/v2/switchmanager/default/save
697      *
698      * </pre>
699      */
700     @Path("/{containerName}/save")
701     @POST
702     @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
703     @StatusCodes({
704         @ResponseCode(code = 200, condition = "Operation successful"),
705         @ResponseCode(code = 401, condition = "User not authorized to perform this operation"),
706         @ResponseCode(code = 404, condition = "The containerName is not found"),
707         @ResponseCode(code = 500, condition = "Failed to save switch configuration. Failure Reason included in HTTP Error response"),
708         @ResponseCode(code = 503, condition = "One or more of Controller Services are unavailable") })
709     public Response saveSwitchConfig(@PathParam("containerName") String containerName) {
710
711         if (!isValidContainer(containerName)) {
712             throw new ResourceNotFoundException("Container " + containerName + " does not exist.");
713         }
714         if (!NorthboundUtils.isAuthorized(getUserName(), containerName, Privilege.WRITE, this)) {
715             throw new UnauthorizedException("User is not authorized to perform this operation on container "
716                     + containerName);
717         }
718         ISwitchManager switchManager = getIfSwitchManagerService(containerName);
719         if (switchManager == null) {
720             throw new ServiceUnavailableException("Switch Manager " + RestMessages.SERVICEUNAVAILABLE.toString());
721         }
722
723         Status ret = switchManager.saveSwitchConfig();
724         if (ret.isSuccess()) {
725             return Response.ok().build();
726         }
727         throw new InternalServerErrorException(ret.getDescription());
728     }
729
730     private Node handleNodeAvailability(String containerName, String nodeType, String nodeId) {
731
732         Node node = Node.fromString(nodeType, nodeId);
733         if (node == null) {
734             throw new ResourceNotFoundException(nodeId + " : " + RestMessages.NONODE.toString());
735         }
736
737         ISwitchManager sm = (ISwitchManager) ServiceHelper.getInstance(ISwitchManager.class, containerName, this);
738
739         if (sm == null) {
740             throw new ServiceUnavailableException("Switch Manager " + RestMessages.SERVICEUNAVAILABLE.toString());
741         }
742
743         if (!sm.getNodes().contains(node)) {
744             throw new ResourceNotFoundException(node.toString() + " : " + RestMessages.NONODE.toString());
745         }
746         return node;
747     }
748
749     private void handleNodeConnectorAvailability(String containerName, Node node, String nodeConnectorType,
750             String nodeConnectorId) {
751
752         NodeConnector nc = NodeConnector.fromStringNoNode(nodeConnectorType, nodeConnectorId, node);
753         if (nc == null) {
754             throw new ResourceNotFoundException(nc + " : " + RestMessages.NORESOURCE.toString());
755         }
756
757         ISwitchManager sm = (ISwitchManager) ServiceHelper.getInstance(ISwitchManager.class, containerName, this);
758
759         if (sm == null) {
760             throw new ServiceUnavailableException("Switch Manager " + RestMessages.SERVICEUNAVAILABLE.toString());
761         }
762
763         if (!sm.getNodeConnectors(node).contains(nc)) {
764             throw new ResourceNotFoundException(nc.toString() + " : " + RestMessages.NORESOURCE.toString());
765         }
766     }
767
768     private boolean isValidContainer(String containerName) {
769         if (containerName.equals(GlobalConstants.DEFAULT.toString())) {
770             return true;
771         }
772         IContainerManager containerManager = (IContainerManager) ServiceHelper.getGlobalInstance(
773                 IContainerManager.class, this);
774         if (containerManager == null) {
775             throw new InternalServerErrorException(RestMessages.INTERNALERROR.toString());
776         }
777         if (containerManager.getContainerNames().contains(containerName)) {
778             return true;
779         }
780         return false;
781     }
782
783 }