2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.openecomp.aai.restcore;
23 import java.io.UnsupportedEncodingException;
25 import java.util.ArrayList;
26 import java.util.List;
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;
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;
49 import com.att.eelf.configuration.EELFLogger;
50 import com.att.eelf.configuration.EELFManager;
51 import com.google.common.base.Joiner;
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
62 public class RESTAPI {
64 private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(RESTAPI.class);
66 protected final String COMPONENT = "aairest";
72 GET, PUT, POST, DELETE
76 * Gets the from app id.
78 * @param headers the headers
79 * @param logline the logline
80 * @return the from app id
81 * @throws AAIException the AAI exception
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;
94 if (fromAppId == null) {
95 throw new AAIException("AAI_4009");
98 LoggingContext.partnerName(fromAppId);
106 * @param headers the headers
107 * @param logline the logline
108 * @return the trans id
109 * @throws AAIException the AAI exception
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;
122 if (transId == null) {
123 throw new AAIException("AAI_4010");
126 LoggingContext.requestId(transId);
137 protected String genDate() {
138 FormatDate fd = new FormatDate( "YYMMdd-HH:mm:ss:SSS");
140 return fd.getDateTime();
144 * Gets the media type.
146 * @param mediaTypeList the media type list
147 * @return the media type
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;
160 /* ----------helpers for common consumer actions ----------- */
165 * @param depthParam the depth param
167 * @throws AAIException the AAI exception
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")){
173 depth = Integer.valueOf(depthParam);
174 } catch (Exception e) {
175 throw new AAIException("AAI_4016");
182 * Consumer exception response generator.
184 * @param headers the headers
185 * @param info the info
186 * @param templateAction the template action
188 * @return the response
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());
197 .status(e.getErrorObject().getHTTPResponseCode())
198 .entity(ErrorLogHelper.getRESTAPIErrorResponseWithLogging(headers.getAcceptableMediaTypes(), e, templateVars))
203 * Validate introspector.
206 * @param loader the loader
208 * @param validateRequired the validate required
209 * @throws AAIException the AAI exception
210 * @throws UnsupportedEncodingException the unsupported encoding exception
212 protected void validateIntrospector(Introspector obj, Loader loader, URI uri, HttpMethod method) throws AAIException, UnsupportedEncodingException {
214 int maximumDepth = AAIProperties.MAXIMUM_DEPTH;
215 boolean validateRequired = true;
216 if (method.equals(HttpMethod.MERGE_PATCH)) {
217 validateRequired = false;
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))
228 boolean result = validator.validate(obj);
230 result = validator.resolveIssues();
233 List<String> messages = new ArrayList<>();
234 for (Issue issue : validator.getIssues()) {
235 if (!issue.isResolved()) {
236 messages.add(issue.getDetail());
239 String errors = Joiner.on(",").join(messages);
240 throw new AAIException("AAI_3000", errors);
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");
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;
258 type = DBConnectionType.CACHED;
265 * Gets the input media type.
267 * @param mediaType the media type
268 * @return the input media type
270 protected String getInputMediaType(MediaType mediaType) {
271 String result = mediaType.getType() + "/" + mediaType.getSubtype();