Bug 5431: Fixing bug & adding new tests for code coverage
[neutron.git] / northbound-api / src / main / java / org / opendaylight / neutron / northbound / api / NeutronPortsNorthbound.java
1 /*
2  * Copyright (c) 2013, 2015 IBM Corporation 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.neutron.northbound.api;
10
11 import java.net.HttpURLConnection;
12
13 import java.util.ArrayList;
14 import java.util.Iterator;
15 import java.util.List;
16
17 import javax.ws.rs.Consumes;
18 import javax.ws.rs.DELETE;
19 import javax.ws.rs.DefaultValue;
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.QueryParam;
27 import javax.ws.rs.core.Context;
28 import javax.ws.rs.core.MediaType;
29 import javax.ws.rs.core.Response;
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.opendaylight.neutron.spi.INeutronNetworkCRUD;
35 import org.opendaylight.neutron.spi.INeutronPortAware;
36 import org.opendaylight.neutron.spi.INeutronPortCRUD;
37 import org.opendaylight.neutron.spi.INeutronSubnetCRUD;
38 import org.opendaylight.neutron.spi.NeutronCRUDInterfaces;
39 import org.opendaylight.neutron.spi.NeutronPort;
40
41 /**
42  * Neutron Northbound REST APIs.<br>
43  * This class provides REST APIs for managing neutron port objects
44  *
45  * <br>
46  * <br>
47  * Authentication scheme : <b>HTTP Basic</b><br>
48  * Authentication realm : <b>opendaylight</b><br>
49  * Transport : <b>HTTP and HTTPS</b><br>
50  * <br>
51  * HTTPS Authentication is disabled by default. Administrator can enable it in
52  * tomcat-server.xml after adding a proper keystore / SSL certificate from a
53  * trusted authority.<br>
54  * More info :
55  * http://tomcat.apache.org/tomcat-7.0-doc/ssl-howto.html#Configuration
56  *
57  */
58
59 @Path("/ports")
60 public class NeutronPortsNorthbound
61     extends AbstractNeutronNorthboundIAware<NeutronPort, NeutronPortRequest, INeutronPortCRUD, INeutronPortAware> {
62
63     private static final String RESOURCE_NAME = "Port";
64
65     @Override
66     protected String getResourceName() {
67         return RESOURCE_NAME;
68     }
69
70     @Override
71     protected NeutronPort extractFields(NeutronPort o, List<String> fields) {
72         return o.extractFields(fields);
73     }
74
75     private NeutronCRUDInterfaces getNeutronInterfaces(boolean needNetworks, boolean needSubnets) {
76         NeutronCRUDInterfaces answer = new NeutronCRUDInterfaces().fetchINeutronPortCRUD(this);
77         if (answer.getPortInterface() == null) {
78             throw new ServiceUnavailableException(serviceUnavailable());
79         }
80         if (needNetworks) {
81             answer = answer.fetchINeutronNetworkCRUD( this);
82             if (answer.getNetworkInterface() == null) {
83                 throw new ServiceUnavailableException("Network CRUD Interface "
84                         + RestMessages.SERVICEUNAVAILABLE.toString());
85             }
86         }
87         if (needSubnets) {
88             answer = answer.fetchINeutronSubnetCRUD( this);
89             if (answer.getSubnetInterface() == null) {
90                 throw new ServiceUnavailableException("Subnet CRUD Interface "
91                         + RestMessages.SERVICEUNAVAILABLE.toString());
92             }
93         }
94         return answer;
95     }
96
97     @Override
98     protected INeutronPortCRUD getNeutronCRUD() {
99         return getNeutronInterfaces(false, false).getPortInterface();
100     }
101
102     @Override
103     protected NeutronPortRequest newNeutronRequest(NeutronPort o) {
104         return new NeutronPortRequest(o);
105     }
106
107     @Override
108     protected Object[] getInstances() {
109         return NeutronUtil.getInstances(INeutronPortAware.class, this);
110     }
111
112     @Override
113     protected int canCreate(Object instance, NeutronPort singleton) {
114         INeutronPortAware service = (INeutronPortAware) instance;
115         return service.canCreatePort(singleton);
116     }
117
118     @Override
119     protected void created(Object instance, NeutronPort singleton) {
120         INeutronPortAware service = (INeutronPortAware) instance;
121         service.neutronPortCreated(singleton);
122     }
123
124     @Override
125     protected int canUpdate(Object instance, NeutronPort delta, NeutronPort original) {
126         INeutronPortAware service = (INeutronPortAware) instance;
127         return service.canUpdatePort(delta, original);
128     }
129
130     @Override
131     protected void updated(Object instance, NeutronPort updated) {
132         INeutronPortAware service = (INeutronPortAware) instance;
133         service.neutronPortUpdated(updated);
134     }
135
136     @Override
137     protected int canDelete(Object instance, NeutronPort singleton) {
138         INeutronPortAware service = (INeutronPortAware) instance;
139         return service.canDeletePort(singleton);
140     }
141
142     @Override
143     protected void deleted(Object instance, NeutronPort singleton) {
144         INeutronPortAware service = (INeutronPortAware) instance;
145         service.neutronPortDeleted(singleton);
146     }
147
148     @Context
149     UriInfo uriInfo;
150
151     /**
152      * Returns a list of all Ports */
153
154     @GET
155     @Produces({ MediaType.APPLICATION_JSON })
156     //@TypeHint(OpenStackPorts.class)
157     @StatusCodes({
158         @ResponseCode(code = HttpURLConnection.HTTP_OK, condition = "Operation successful"),
159         @ResponseCode(code = HttpURLConnection.HTTP_UNAUTHORIZED, condition = "Unauthorized"),
160         @ResponseCode(code = HttpURLConnection.HTTP_NOT_IMPLEMENTED, condition = "Not Implemented"),
161         @ResponseCode(code = HttpURLConnection.HTTP_UNAVAILABLE, condition = "No providers available") })
162     public Response listPorts(
163             // return fields
164             @QueryParam("fields") List<String> fields,
165             // note: openstack isn't clear about filtering on lists, so we aren't handling them
166             @QueryParam("id") String queryID,
167             @QueryParam("network_id") String queryNetworkID,
168             @QueryParam("name") String queryName,
169             @QueryParam("admin_state_up") Boolean queryAdminStateUp,
170             @QueryParam("status") String queryStatus,
171             @QueryParam("mac_address") String queryMACAddress,
172             @QueryParam("device_id") String queryDeviceID,
173             @QueryParam("device_owner") String queryDeviceOwner,
174             @QueryParam("tenant_id") String queryTenantID,
175             // linkTitle
176             @QueryParam("limit") Integer limit,
177             @QueryParam("marker") String marker,
178             @DefaultValue("false") @QueryParam("page_reverse") Boolean pageReverse
179             // sorting not supported
180             ) {
181         INeutronPortCRUD portInterface = getNeutronInterfaces(false, false).getPortInterface();
182         List<NeutronPort> allPorts = portInterface.getAllPorts();
183         List<NeutronPort> ans = new ArrayList<NeutronPort>();
184         Iterator<NeutronPort> i = allPorts.iterator();
185         while (i.hasNext()) {
186             NeutronPort oSS = i.next();
187             if ((queryID == null || queryID.equals(oSS.getID())) &&
188                     (queryNetworkID == null || queryNetworkID.equals(oSS.getNetworkUUID())) &&
189                     (queryName == null || queryName.equals(oSS.getName())) &&
190                     (queryAdminStateUp == null || queryAdminStateUp.equals(oSS.getAdminStateUp())) &&
191                     (queryStatus == null || queryStatus.equals(oSS.getStatus())) &&
192                     (queryMACAddress == null || queryMACAddress.equals(oSS.getMacAddress())) &&
193                     (queryDeviceID == null || queryDeviceID.equals(oSS.getDeviceID())) &&
194                     (queryDeviceOwner == null || queryDeviceOwner.equals(oSS.getDeviceOwner())) &&
195                     (queryTenantID == null || queryTenantID.equals(oSS.getTenantID()))) {
196                 if (fields.size() > 0) {
197                     ans.add(extractFields(oSS,fields));
198                 } else {
199                     ans.add(oSS);
200                 }
201             }
202         }
203
204         if (limit != null && ans.size() > 1) {
205             // Return a paginated request
206             NeutronPortRequest request = (NeutronPortRequest) PaginatedRequestFactory.createRequest(limit,
207                     marker, pageReverse, uriInfo, ans, NeutronPort.class);
208             return Response.status(HttpURLConnection.HTTP_OK).entity(request).build();
209         }
210
211         return Response.status(HttpURLConnection.HTTP_OK).entity(
212                 new NeutronPortRequest(ans)).build();
213     }
214
215     /**
216      * Returns a specific Port */
217
218     @Path("{portUUID}")
219     @GET
220     @Produces({ MediaType.APPLICATION_JSON })
221     //@TypeHint(OpenStackPorts.class)
222     @StatusCodes({
223         @ResponseCode(code = HttpURLConnection.HTTP_OK, condition = "Operation successful"),
224         @ResponseCode(code = HttpURLConnection.HTTP_UNAUTHORIZED, condition = "Unauthorized"),
225         @ResponseCode(code = HttpURLConnection.HTTP_NOT_FOUND, condition = "Not Found"),
226         @ResponseCode(code = HttpURLConnection.HTTP_NOT_IMPLEMENTED, condition = "Not Implemented"),
227         @ResponseCode(code = HttpURLConnection.HTTP_UNAVAILABLE, condition = "No providers available") })
228     public Response showPort(
229             @PathParam("portUUID") String portUUID,
230             // return fields
231             @QueryParam("fields") List<String> fields ) {
232         return show(portUUID, fields);
233     }
234
235     /**
236      * Creates new Ports */
237
238     @POST
239     @Produces({ MediaType.APPLICATION_JSON })
240     @Consumes({ MediaType.APPLICATION_JSON })
241     //@TypeHint(OpenStackPorts.class)
242     @StatusCodes({
243         @ResponseCode(code = HttpURLConnection.HTTP_CREATED, condition = "Created"),
244         @ResponseCode(code = HttpURLConnection.HTTP_UNAVAILABLE, condition = "No providers available") })
245     public Response createPorts(final NeutronPortRequest input) {
246         getNeutronInterfaces(true, true); // Ensure that services for networks and subnets are loaded
247         return create(input);
248     }
249
250     @Override
251     protected void updateDelta(String uuid, NeutronPort delta, NeutronPort original) {
252         /*
253          * note: what we would like to get is the complete object as it
254          * is known by neutron.  Until then, patch what we *do* get
255          * so that we don't lose already known information
256          */
257         if (delta.getID() == null) {
258             delta.setID(uuid);
259         }
260         if (delta.getTenantID() == null) {
261             delta.setTenantID(original.getTenantID());
262         }
263         if (delta.getNetworkUUID() == null) {
264             delta.setNetworkUUID(original.getNetworkUUID());
265         }
266         if (delta.getMacAddress() == null) {
267             delta.setMacAddress(original.getMacAddress());
268         }
269         if (delta.getFixedIPs() == null) {
270             delta.setFixedIPs(original.getFixedIPs());
271         }
272     }
273
274     /**
275      * Updates a Port */
276
277     @Path("{portUUID}")
278     @PUT
279     @Produces({ MediaType.APPLICATION_JSON })
280     @Consumes({ MediaType.APPLICATION_JSON })
281     //@TypeHint(OpenStackPorts.class)
282     @StatusCodes({
283         @ResponseCode(code = HttpURLConnection.HTTP_OK, condition = "Operation successful"),
284         @ResponseCode(code = HttpURLConnection.HTTP_UNAVAILABLE, condition = "No providers available") })
285     public Response updatePort(
286             @PathParam("portUUID") String portUUID,
287             NeutronPortRequest input
288             ) {
289         //        TODO: Support change of security groups
290         // update the port and return the modified object
291         return update(portUUID, input);
292     }
293
294     /**
295      * Deletes a Port */
296
297     @Path("{portUUID}")
298     @DELETE
299     @StatusCodes({
300         @ResponseCode(code = HttpURLConnection.HTTP_NO_CONTENT, condition = "No Content"),
301         @ResponseCode(code = HttpURLConnection.HTTP_UNAVAILABLE, condition = "No providers available") })
302     public Response deletePort(
303             @PathParam("portUUID") String portUUID) {
304         return delete(portUUID);
305     }
306 }