Bug 5478 - northbound: improve 404 check on update/delete
[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             @QueryParam("port_security_enabled") Boolean queryPortSecurityEnabled,
176             // linkTitle
177             @QueryParam("limit") Integer limit,
178             @QueryParam("marker") String marker,
179             @DefaultValue("false") @QueryParam("page_reverse") Boolean pageReverse
180             // sorting not supported
181             ) {
182         INeutronPortCRUD portInterface = getNeutronInterfaces(false, false).getPortInterface();
183         List<NeutronPort> allPorts = portInterface.getAllPorts();
184         List<NeutronPort> ans = new ArrayList<NeutronPort>();
185         Iterator<NeutronPort> i = allPorts.iterator();
186         while (i.hasNext()) {
187             NeutronPort oSS = i.next();
188             if ((queryID == null || queryID.equals(oSS.getID())) &&
189                     (queryNetworkID == null || queryNetworkID.equals(oSS.getNetworkUUID())) &&
190                     (queryName == null || queryName.equals(oSS.getName())) &&
191                     (queryAdminStateUp == null || queryAdminStateUp.equals(oSS.getAdminStateUp())) &&
192                     (queryStatus == null || queryStatus.equals(oSS.getStatus())) &&
193                     (queryMACAddress == null || queryMACAddress.equals(oSS.getMacAddress())) &&
194                     (queryDeviceID == null || queryDeviceID.equals(oSS.getDeviceID())) &&
195                     (queryDeviceOwner == null || queryDeviceOwner.equals(oSS.getDeviceOwner())) &&
196                     (queryTenantID == null || queryTenantID.equals(oSS.getTenantID())) &&
197                     (queryPortSecurityEnabled == null || queryPortSecurityEnabled.equals(oSS.getPortSecurityEnabled()))) {
198                 if (fields.size() > 0) {
199                     ans.add(extractFields(oSS,fields));
200                 } else {
201                     ans.add(oSS);
202                 }
203             }
204         }
205
206         if (limit != null && ans.size() > 1) {
207             // Return a paginated request
208             NeutronPortRequest request = (NeutronPortRequest) PaginatedRequestFactory.createRequest(limit,
209                     marker, pageReverse, uriInfo, ans, NeutronPort.class);
210             return Response.status(HttpURLConnection.HTTP_OK).entity(request).build();
211         }
212
213         return Response.status(HttpURLConnection.HTTP_OK).entity(
214                 new NeutronPortRequest(ans)).build();
215     }
216
217     /**
218      * Returns a specific Port */
219
220     @Path("{portUUID}")
221     @GET
222     @Produces({ MediaType.APPLICATION_JSON })
223     //@TypeHint(OpenStackPorts.class)
224     @StatusCodes({
225         @ResponseCode(code = HttpURLConnection.HTTP_OK, condition = "Operation successful"),
226         @ResponseCode(code = HttpURLConnection.HTTP_UNAUTHORIZED, condition = "Unauthorized"),
227         @ResponseCode(code = HttpURLConnection.HTTP_NOT_FOUND, condition = "Not Found"),
228         @ResponseCode(code = HttpURLConnection.HTTP_NOT_IMPLEMENTED, condition = "Not Implemented"),
229         @ResponseCode(code = HttpURLConnection.HTTP_UNAVAILABLE, condition = "No providers available") })
230     public Response showPort(
231             @PathParam("portUUID") String portUUID,
232             // return fields
233             @QueryParam("fields") List<String> fields ) {
234         return show(portUUID, fields);
235     }
236
237     /**
238      * Creates new Ports */
239
240     @POST
241     @Produces({ MediaType.APPLICATION_JSON })
242     @Consumes({ MediaType.APPLICATION_JSON })
243     //@TypeHint(OpenStackPorts.class)
244     @StatusCodes({
245         @ResponseCode(code = HttpURLConnection.HTTP_CREATED, condition = "Created"),
246         @ResponseCode(code = HttpURLConnection.HTTP_UNAVAILABLE, condition = "No providers available") })
247     public Response createPorts(final NeutronPortRequest input) {
248         getNeutronInterfaces(true, true); // Ensure that services for networks and subnets are loaded
249         return create(input);
250     }
251
252     @Override
253     protected void updateDelta(String uuid, NeutronPort delta, NeutronPort original) {
254         /*
255          * note: what we would like to get is the complete object as it
256          * is known by neutron.  Until then, patch what we *do* get
257          * so that we don't lose already known information
258          */
259         if (delta.getID() == null) {
260             delta.setID(uuid);
261         }
262         if (delta.getTenantID() == null) {
263             delta.setTenantID(original.getTenantID());
264         }
265         if (delta.getNetworkUUID() == null) {
266             delta.setNetworkUUID(original.getNetworkUUID());
267         }
268         if (delta.getMacAddress() == null) {
269             delta.setMacAddress(original.getMacAddress());
270         }
271         if (delta.getFixedIPs() == null) {
272             delta.setFixedIPs(original.getFixedIPs());
273         }
274     }
275
276     /**
277      * Updates a Port */
278
279     @Path("{portUUID}")
280     @PUT
281     @Produces({ MediaType.APPLICATION_JSON })
282     @Consumes({ MediaType.APPLICATION_JSON })
283     //@TypeHint(OpenStackPorts.class)
284     @StatusCodes({
285         @ResponseCode(code = HttpURLConnection.HTTP_OK, condition = "Operation successful"),
286         @ResponseCode(code = HttpURLConnection.HTTP_NOT_FOUND, condition = "Not Found"),
287         @ResponseCode(code = HttpURLConnection.HTTP_UNAVAILABLE, condition = "No providers available") })
288     public Response updatePort(
289             @PathParam("portUUID") String portUUID,
290             NeutronPortRequest input
291             ) {
292         //        TODO: Support change of security groups
293         // update the port and return the modified object
294         return update(portUUID, input);
295     }
296
297     /**
298      * Deletes a Port */
299
300     @Path("{portUUID}")
301     @DELETE
302     @StatusCodes({
303         @ResponseCode(code = HttpURLConnection.HTTP_NO_CONTENT, condition = "No Content"),
304         @ResponseCode(code = HttpURLConnection.HTTP_NOT_FOUND, condition = "Not Found"),
305         @ResponseCode(code = HttpURLConnection.HTTP_UNAVAILABLE, condition = "No providers available") })
306     public Response deletePort(
307             @PathParam("portUUID") String portUUID) {
308         return delete(portUUID);
309     }
310 }