18aef07353b520ce49767d094fcd31a5b7117d44
[aai/aai-common.git] / aai-core / src / main / java / org / openecomp / aai / restcore / RESTAPI.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * org.openecomp.aai
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.openecomp.aai.restcore;
22
23 import java.io.UnsupportedEncodingException;
24 import java.net.URI;
25 import java.util.ArrayList;
26 import java.util.List;
27
28 import javax.ws.rs.core.HttpHeaders;
29 import javax.ws.rs.core.MediaType;
30 import javax.ws.rs.core.Response;
31 import javax.ws.rs.core.UriInfo;
32
33 import org.openecomp.aai.db.props.AAIProperties;
34 import org.openecomp.aai.dbmap.DBConnectionType;
35 import org.openecomp.aai.exceptions.AAIException;
36 import org.openecomp.aai.introspection.Introspector;
37 import org.openecomp.aai.introspection.Loader;
38 import org.openecomp.aai.introspection.tools.CreateUUID;
39 import org.openecomp.aai.introspection.tools.DefaultFields;
40 import org.openecomp.aai.introspection.tools.InjectKeysFromURI;
41 import org.openecomp.aai.introspection.tools.IntrospectorValidator;
42 import org.openecomp.aai.introspection.tools.Issue;
43 import org.openecomp.aai.introspection.tools.RemoveNonVisibleProperty;
44 import org.openecomp.aai.logging.ErrorLogHelper;
45 import org.openecomp.aai.logging.LoggingContext;
46 import org.openecomp.aai.util.AAIConfig;
47 import org.openecomp.aai.util.FormatDate;
48
49 import com.att.eelf.configuration.EELFLogger;
50 import com.att.eelf.configuration.EELFManager;
51 import com.google.common.base.Joiner;
52
53
54 /**
55  * Base class for AAI REST API classes.
56  * Provides method to validate header information
57  * TODO should authenticate caller and authorize them for the API they are calling
58  * TODO should store the transaction
59  
60  *
61  */
62 public class RESTAPI {
63         
64         private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(RESTAPI.class);
65
66         protected final String COMPONENT = "aairest";
67
68         /**
69          * The Enum Action.
70          */
71         public enum Action {
72                 GET, PUT, POST, DELETE
73         };
74
75         /**
76          * Gets the from app id.
77          *
78          * @param headers the headers
79          * @param logline the logline
80          * @return the from app id
81          * @throws AAIException the AAI exception
82          */
83         protected String getFromAppId(HttpHeaders headers) throws AAIException { 
84                 String fromAppId = null;
85                 if (headers != null) {
86                         List<String> fromAppIdHeader = headers.getRequestHeader("X-FromAppId");
87                         if (fromAppIdHeader != null) {
88                                 for (String fromAppIdValue : fromAppIdHeader) {
89                                         fromAppId = fromAppIdValue;
90                                 }
91                         } 
92                 }
93
94                 if (fromAppId == null) {
95                         throw new AAIException("AAI_4009");
96                 }
97
98                 LoggingContext.partnerName(fromAppId);
99
100                 return fromAppId;
101         }
102         
103         /**
104          * Gets the trans id.
105          *
106          * @param headers the headers
107          * @param logline the logline
108          * @return the trans id
109          * @throws AAIException the AAI exception
110          */
111         protected String getTransId(HttpHeaders headers) throws AAIException { 
112                 String transId = null;
113                 if (headers != null) {
114                         List<String> transIdHeader = headers.getRequestHeader("X-TransactionId");
115                         if (transIdHeader != null) {
116                                 for (String transIdValue : transIdHeader) {
117                                         transId = transIdValue;
118                                 }
119                         }
120                 }
121
122                 if (transId == null) {
123                         throw new AAIException("AAI_4010");
124                 }
125
126                 LoggingContext.requestId(transId);
127
128                 return transId;
129         }
130         
131         
132         /**
133          * Gen date.
134          *
135          * @return the string
136          */
137         protected String genDate() {
138                 FormatDate fd = new FormatDate( "YYMMdd-HH:mm:ss:SSS");
139                 
140                 return fd.getDateTime();
141         }
142
143         /**
144          * Gets the media type.
145          *
146          * @param mediaTypeList the media type list
147          * @return the media type
148          */
149         protected String getMediaType(List <MediaType> mediaTypeList) {
150                 String mediaType = MediaType.APPLICATION_JSON;  // json is the default    
151                 for (MediaType mt : mediaTypeList) {
152                         if (MediaType.APPLICATION_XML_TYPE.isCompatible(mt)) {
153                                 mediaType = MediaType.APPLICATION_XML;
154                         } 
155                 }
156                 return mediaType;
157         }
158         
159
160         /* ----------helpers for common consumer actions ----------- */
161         
162         /**
163          * Sets the depth.
164          *
165          * @param depthParam the depth param
166          * @return the int
167          * @throws AAIException the AAI exception
168          */
169         protected int setDepth(String depthParam) throws AAIException {
170                 int depth = AAIProperties.MAXIMUM_DEPTH; //default 
171                 if (depthParam != null && depthParam.length() > 0 && !depthParam.equals("all")){
172                         try {
173                                 depth = Integer.valueOf(depthParam);
174                         } catch (Exception e) {
175                                 throw new AAIException("AAI_4016");
176                         }
177                 }
178                 return depth;
179         }
180
181         /**
182          * Consumer exception response generator.
183          *
184          * @param headers the headers
185          * @param info the info
186          * @param templateAction the template action
187          * @param e the e
188          * @return the response
189          */
190         protected Response consumerExceptionResponseGenerator(HttpHeaders headers, UriInfo info, HttpMethod templateAction, AAIException e) {
191                 ArrayList<String> templateVars = new ArrayList<String>();
192                 templateVars.add(templateAction.toString()); //GET, PUT, etc
193                 templateVars.add(info.getPath().toString());
194                 templateVars.addAll(e.getTemplateVars());
195
196                 return Response
197                                 .status(e.getErrorObject().getHTTPResponseCode())
198                                 .entity(ErrorLogHelper.getRESTAPIErrorResponseWithLogging(headers.getAcceptableMediaTypes(), e, templateVars))
199                                 .build();
200         }
201         
202         /**
203          * Validate introspector.
204          *
205          * @param obj the obj
206          * @param loader the loader
207          * @param uri the uri
208          * @param validateRequired the validate required
209          * @throws AAIException the AAI exception
210          * @throws UnsupportedEncodingException the unsupported encoding exception
211          */
212         protected void validateIntrospector(Introspector obj, Loader loader, URI uri, HttpMethod method) throws AAIException, UnsupportedEncodingException {
213                 
214                 int maximumDepth = AAIProperties.MAXIMUM_DEPTH;
215                 boolean validateRequired = true;
216                 if (method.equals(HttpMethod.MERGE_PATCH)) {
217                         validateRequired = false;
218                         maximumDepth = 0;
219                 }
220                 IntrospectorValidator validator = new IntrospectorValidator.Builder()
221                                 .validateRequired(validateRequired)
222                                 .restrictDepth(maximumDepth)
223                                 .addResolver(new RemoveNonVisibleProperty())
224                                 .addResolver(new CreateUUID())
225                                 .addResolver(new DefaultFields())
226                                 .addResolver(new InjectKeysFromURI(loader, uri))
227                                 .build();
228                 boolean result = validator.validate(obj);
229                 if (!result) {
230                         result = validator.resolveIssues();
231                 }
232                 if (!result) {
233                         List<String> messages = new ArrayList<>();
234                         for (Issue issue : validator.getIssues()) {
235                                 if (!issue.isResolved()) {
236                                         messages.add(issue.getDetail());
237                                 }
238                         }
239                         String errors = Joiner.on(",").join(messages);
240                         throw new AAIException("AAI_3000", errors);
241                 }
242                 //check that key in payload and key in request uri are the same
243         String objURI = obj.getURI();
244         //if requested object is a parent objURI will have a leading slash the input uri will lack
245         //this adds that leading slash for the comparison
246         String testURI = "/" + uri.getRawPath();
247         if (!testURI.endsWith(objURI)) {
248                 throw new AAIException("AAI_3000", "uri and payload keys don't match");
249         }
250         }
251         
252         protected DBConnectionType determineConnectionType(String fromAppId, String realTime) {
253                 DBConnectionType type = DBConnectionType.REALTIME;
254                 boolean isRealTimeClient = AAIConfig.get("aai.realtime.clients", "").contains(fromAppId);
255                 if (isRealTimeClient || realTime != null) {
256                         type = DBConnectionType.REALTIME;
257                 } else {
258                         type = DBConnectionType.CACHED;
259                 }
260                 
261                 return type;
262         }
263         
264         /**
265          * Gets the input media type.
266          *
267          * @param mediaType the media type
268          * @return the input media type
269          */
270         protected String getInputMediaType(MediaType mediaType) {
271                 String result = mediaType.getType() + "/" + mediaType.getSubtype();
272                 
273                 return result;
274                 
275         }
276
277 }