bb9158f53a97624c4016b5b677c1765aab919409
[neutron.git] / northbound-api / src / main / java / org / opendaylight / neutron / northbound / api / AbstractNeutronNorthbound.java
1 /*
2  * Copyright (c) 2018 Intel 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 package org.opendaylight.neutron.northbound.api;
9
10 import static org.opendaylight.neutron.spi.INeutronCRUD.Result.DependencyMissing;
11 import static org.opendaylight.neutron.spi.INeutronCRUD.Result.DoesNotExist;
12
13 import java.lang.reflect.Constructor;
14 import java.lang.reflect.InvocationTargetException;
15 import java.lang.reflect.ParameterizedType;
16 import java.net.HttpURLConnection;
17 import java.util.List;
18 import java.util.Objects;
19 import javax.ws.rs.core.Response;
20 import org.opendaylight.neutron.spi.INeutronCRUD;
21 import org.opendaylight.neutron.spi.INeutronCRUD.Result;
22 import org.opendaylight.neutron.spi.INeutronObject;
23 import org.opendaylight.yangtools.yang.common.OperationFailedException;
24
25 public abstract class AbstractNeutronNorthbound<T extends INeutronObject<T>, R extends INeutronRequest<T>,
26         I extends INeutronCRUD<T>> {
27
28     // T extends INeutronObject<T> as 0th type argument
29     private static final int NEUTRON_ARGUMENT_TYPE_INDEX = 0;
30     // NeutronRequest extends INeutronRequest<T> as 1st type argument
31     private static final int NEUTRON_REQUEST_TYPE_INDEX = 1;
32
33     protected static final int HTTP_OK_BOTTOM = 200;
34     protected static final int HTTP_OK_TOP = 299;
35     private static final int HTTP_MISSING_DEPENDENCY = 442; // see NEUTRON-158 (also in neutron.e2etest.HttpUtils)
36
37     private static final String INTERFACE_NAME_BASE = " CRUD Interface";
38     private static final String UUID_NO_EXIST_BASE = " UUID does not exist.";
39
40     private final I neutronCRUD;
41
42     protected AbstractNeutronNorthbound(I neutronCRUD) {
43         this.neutronCRUD = Objects.requireNonNull(neutronCRUD, "neutronCRUD");
44     }
45
46     protected final String serviceUnavailable() {
47         return getResourceName() + INTERFACE_NAME_BASE + RestMessages.SERVICEUNAVAILABLE.toString();
48     }
49
50     protected final String uuidNoExist() {
51         return getResourceName() + UUID_NO_EXIST_BASE;
52     }
53
54     protected abstract String getResourceName();
55
56     private <K> Class<K> getActualTypeArgument(final int typeIndex) {
57         ParameterizedType parameterizedType = (ParameterizedType) getClass().getGenericSuperclass();
58         @SuppressWarnings("unchecked")
59         Class<K> cls = (Class<K>) parameterizedType.getActualTypeArguments()[typeIndex];
60         return cls;
61     }
62
63     private R newNeutronRequest(T neutronObject) {
64         // return new R(neutronObject)
65
66         // argumentClass = T.class
67         Class<T> argumentClass = getActualTypeArgument(NEUTRON_ARGUMENT_TYPE_INDEX);
68         // cls = NeturonRequest.class
69         Class<R> cls = getActualTypeArgument(NEUTRON_REQUEST_TYPE_INDEX);
70         try {
71             // ctor = R constructor
72             Constructor<R> ctor = cls.getDeclaredConstructor(argumentClass);
73             return ctor.newInstance(neutronObject);
74         } catch (NoSuchMethodException | InstantiationException
75                  | IllegalAccessException | InvocationTargetException e) {
76             // This case shouldn't happen
77             throw new IllegalArgumentException(e);
78         }
79     }
80
81     protected I getNeutronCRUD() {
82         return this.neutronCRUD;
83     }
84
85     protected Response show(String uuid, List<String> returnFields)
86             throws DatastoreOperationFailedWebApplicationException {
87         try {
88             T ans = neutronCRUD.get(uuid);
89             if (ans == null) {
90                 throw new ResourceNotFoundException(uuidNoExist());
91             }
92
93             if (returnFields.size() > 0) {
94                 return Response.status(HttpURLConnection.HTTP_OK)
95                         .entity(newNeutronRequest(ans.extractFields(returnFields))).build();
96             } else {
97                 return Response.status(HttpURLConnection.HTTP_OK).entity(newNeutronRequest(ans)).build();
98             }
99         } catch (OperationFailedException e) {
100             throw new DatastoreOperationFailedWebApplicationException(e);
101         }
102     }
103
104     protected Response create(final R input) throws DatastoreOperationFailedWebApplicationException {
105         try {
106             if (input.isSingleton()) {
107                 T singleton = input.getSingleton();
108
109                 singleton.initDefaults();
110                 if (neutronCRUD.add(singleton).equals(DependencyMissing)) {
111                     return Response.status(HTTP_MISSING_DEPENDENCY).entity(input).build();
112                 }
113             } else {
114                 if (input.getBulk() == null) {
115                     throw new BadRequestException("Invalid requests");
116                 }
117                 for (T test : input.getBulk()) {
118                     test.initDefaults();
119                     if (neutronCRUD.add(test).equals(DependencyMissing)) {
120                         return Response.status(HTTP_MISSING_DEPENDENCY).entity(input).build();
121                     }
122                 }
123             }
124             return Response.status(HttpURLConnection.HTTP_CREATED).entity(input).build();
125         } catch (OperationFailedException e) {
126             throw new DatastoreOperationFailedWebApplicationException(e);
127         }
128     }
129
130     protected void updateDelta(String uuid, T delta, T original) {
131     }
132
133     private boolean checkRevisionNumber(T original, T delta) {
134         // If new update is null ignore the original revision number
135         if (delta.getRevisionNumber() == null) {
136             return false;
137         }
138         // If what is stored is null no need for comparison
139         if (original.getRevisionNumber() == null) {
140             return false;
141         }
142         if (original.getRevisionNumber() > delta.getRevisionNumber()) {
143             return true;
144         }
145         return false;
146     }
147
148     protected Response update(String uuid, final R input) throws DatastoreOperationFailedWebApplicationException {
149         if (!input.isSingleton()) {
150             throw new BadRequestException("Only singleton edit supported");
151         }
152         T delta = input.getSingleton();
153         try {
154             T original = neutronCRUD.get(uuid);
155             if (original == null) {
156                 throw new ResourceNotFoundException(uuidNoExist());
157             }
158             if (checkRevisionNumber(original, delta)) {
159                 return Response.status(HttpURLConnection.HTTP_OK).build();
160             }
161             updateDelta(uuid, delta, original);
162             /*
163              * update the object and return it
164              */
165             Result updateResult = neutronCRUD.update(uuid, delta);
166             if (updateResult.equals(DoesNotExist)) {
167                 throw new ResourceNotFoundException(uuidNoExist());
168             } else if (updateResult.equals(DependencyMissing)) {
169                 return Response.status(HTTP_MISSING_DEPENDENCY).entity(input).build();
170             }
171             T updated = neutronCRUD.get(uuid);
172             return Response.status(HttpURLConnection.HTTP_OK).entity(newNeutronRequest(updated)).build();
173         } catch (OperationFailedException e) {
174             throw new DatastoreOperationFailedWebApplicationException(e);
175         }
176     }
177
178     protected Response delete(String uuid) throws DatastoreOperationFailedWebApplicationException {
179         try {
180             // remove it and return 204 status
181             if (!neutronCRUD.remove(uuid)) {
182                 throw new ResourceNotFoundException(uuidNoExist());
183             } else {
184                 return Response.status(HttpURLConnection.HTTP_NO_CONTENT).build();
185             }
186         } catch (OperationFailedException e) {
187             throw new DatastoreOperationFailedWebApplicationException(e);
188         }
189     }
190 }