Babel service is returning a text/plain content type header with a json response
[aai/babel.git] / src / main / java / org / onap / aai / babel / service / GenerateArtifactsServiceImpl.java
1 /**
2  * ============LICENSE_START=======================================================
3  * org.onap.aai
4  * ================================================================================
5  * Copyright (c) 2017-2019 AT&T Intellectual Property. All rights reserved.
6  * Copyright (c) 2017-2019 European Software Marketing Ltd.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *       http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.aai.babel.service;
23
24 import com.google.gson.Gson;
25 import com.google.gson.GsonBuilder;
26 import com.google.gson.JsonSyntaxException;
27 import java.util.Base64;
28 import java.util.List;
29 import java.util.UUID;
30 import javax.inject.Inject;
31 import javax.servlet.http.HttpServletRequest;
32 import javax.ws.rs.core.*;
33 import javax.ws.rs.core.Response.Status;
34
35 import org.apache.commons.lang3.time.StopWatch;
36 import org.onap.aai.auth.AAIAuthException;
37 import org.onap.aai.auth.AAIMicroServiceAuth;
38 import org.onap.aai.auth.AAIMicroServiceAuthCore;
39 import org.onap.aai.babel.csar.CsarConverterException;
40 import org.onap.aai.babel.csar.CsarToXmlConverter;
41 import org.onap.aai.babel.csar.vnfcatalog.ToscaToCatalogException;
42 import org.onap.aai.babel.csar.vnfcatalog.VnfVendorImageExtractor;
43 import org.onap.aai.babel.logging.ApplicationMsgs;
44 import org.onap.aai.babel.logging.LogHelper;
45 import org.onap.aai.babel.logging.LogHelper.MdcParameter;
46 import org.onap.aai.babel.logging.LogHelper.StatusCode;
47 import org.onap.aai.babel.request.RequestHeaders;
48 import org.onap.aai.babel.service.data.BabelArtifact;
49 import org.onap.aai.babel.service.data.BabelRequest;
50 import org.onap.aai.babel.util.RequestValidationException;
51 import org.onap.aai.babel.util.RequestValidator;
52 import org.springframework.stereotype.Service;
53
54 /**
55  * Generate SDC Artifacts by passing in a CSAR payload, Artifact Name and Artifact version.
56  *
57  */
58 @Service
59 public class GenerateArtifactsServiceImpl implements GenerateArtifactsService {
60     private static final LogHelper applicationLogger = LogHelper.INSTANCE;
61
62     private AAIMicroServiceAuth aaiMicroServiceAuth;
63
64     /**
65      * @param authorization
66      *            the auth module
67      */
68     @Inject
69     public GenerateArtifactsServiceImpl(final AAIMicroServiceAuth authorization) {
70         this.aaiMicroServiceAuth = authorization;
71     }
72
73     /*
74      * (non-Javadoc)
75      *
76      * @see org.onap.aai.babel.service.GenerateArtifactsService#generateArtifacts(javax.ws.rs.core.UriInfo,
77      * javax.ws.rs.core.HttpHeaders, javax.servlet.http.HttpServletRequest, java.lang.String)
78      */
79     @Override
80     public Response generateArtifacts(UriInfo uriInfo, HttpHeaders headers, HttpServletRequest servletRequest,
81             String requestBody) {
82         applicationLogger.startAudit(headers, servletRequest);
83         applicationLogger.info(ApplicationMsgs.BABEL_REQUEST_PAYLOAD,
84                 "Received request: " + headers.getRequestHeaders() + requestBody);
85         applicationLogger.debug(String.format(
86                 "Received request. UriInfo \"%s\", HttpHeaders \"%s\", ServletRequest \"%s\", Request \"%s\"", uriInfo,
87                 headers, servletRequest, requestBody));
88
89         // Additional name/value pairs according to EELF guidelines
90         applicationLogger.setContextValue("Protocol", "https");
91         applicationLogger.setContextValue("Method", "POST");
92         applicationLogger.setContextValue("Path", uriInfo.getPath());
93         applicationLogger.setContextValue("Query", uriInfo.getPathParameters().toString());
94
95         RequestHeaders requestHeaders = new RequestHeaders(headers);
96         applicationLogger.info(ApplicationMsgs.BABEL_REQUEST_PAYLOAD, requestHeaders.toString());
97
98         String requestId = requestHeaders.getCorrelationId();
99         if (requestId == null || !isRequestIDValid(requestId)) {
100             requestId = UUID.randomUUID().toString();
101             applicationLogger.info(ApplicationMsgs.MISSING_REQUEST_ID, requestId);
102             applicationLogger.setContextValue(MdcParameter.REQUEST_ID, requestId);
103         }
104
105         Response response;
106         try {
107             // Get last URI path segment to use for authentication
108             List<PathSegment> pathSegments = uriInfo.getPathSegments();
109             String lastPathSegment = pathSegments.isEmpty() ? "" : pathSegments.get(pathSegments.size() - 1).getPath();
110
111             boolean authorized = aaiMicroServiceAuth.validateRequest(headers, servletRequest,
112                     AAIMicroServiceAuthCore.HTTP_METHODS.POST, lastPathSegment);
113
114             response = authorized ? generateArtifacts(requestBody)
115                     : buildResponse(Status.UNAUTHORIZED, "User not authorized to perform the operation.");
116         } catch (AAIAuthException e) {
117             applicationLogger.error(ApplicationMsgs.PROCESS_REQUEST_ERROR, e);
118             applicationLogger.logAuditError(e);
119             return buildResponse(Status.INTERNAL_SERVER_ERROR,
120                     "Error while processing request. Please check the Babel service logs for more details.\n");
121         }
122
123         StatusCode statusDescription;
124         int statusCode = response.getStatus();
125         if (statusCode / 100 == 2) {
126             statusDescription = StatusCode.COMPLETE;
127         } else {
128             statusDescription = StatusCode.ERROR;
129         }
130         applicationLogger.logAudit(statusDescription, Integer.toString(statusCode),
131                 Response.Status.fromStatusCode(statusCode).getReasonPhrase(), response.getEntity().toString());
132
133         return response;
134     }
135
136     private boolean isRequestIDValid(String requestId) {
137         try {
138             UUID.fromString(requestId);
139         } catch (IllegalArgumentException e) {
140             return false;
141         }
142         return true;
143     }
144
145     /**
146      * Generate XML model artifacts from request body.
147      *
148      * @param requestBody
149      *            the request body in JSON format
150      * @return response object containing the generated XML models
151      */
152     protected Response generateArtifacts(String requestBody) {
153         StopWatch stopwatch = new StopWatch();
154         stopwatch.start();
155
156         Response response;
157
158         try {
159             Gson gson = new GsonBuilder().disableHtmlEscaping().create();
160
161             BabelRequest babelRequest = gson.fromJson(requestBody, BabelRequest.class);
162             new RequestValidator().validateRequest(babelRequest);
163             byte[] csarFile = Base64.getDecoder().decode(babelRequest.getCsar());
164
165             List<BabelArtifact> babelArtifacts = new CsarToXmlConverter().generateXmlFromCsar(csarFile,
166                     babelRequest.getArtifactName(), babelRequest.getArtifactVersion());
167
168             BabelArtifact vendorImageConfiguration = new VnfVendorImageExtractor().extract(csarFile);
169             if (vendorImageConfiguration != null) {
170                 babelArtifacts.add(vendorImageConfiguration);
171             }
172
173             response = buildResponse(Status.OK, gson.toJson(babelArtifacts));
174             applicationLogger.info(ApplicationMsgs.DISTRIBUTION_EVENT,LogHelper.getCallerMethodName(0));
175         } catch (JsonSyntaxException e) {
176             response = processError(ApplicationMsgs.INVALID_REQUEST_JSON, Status.BAD_REQUEST, e, "Malformed request.");
177         } catch (CsarConverterException e) {
178             response = processError(ApplicationMsgs.INVALID_CSAR_FILE, Status.INTERNAL_SERVER_ERROR, e,
179                     "Error converting CSAR artifact to XML model.");
180         } catch (ToscaToCatalogException e) {
181             response = processError(ApplicationMsgs.PROCESSING_VNF_CATALOG_ERROR, Status.INTERNAL_SERVER_ERROR, e,
182                     "Error converting CSAR artifact to VNF catalog.");
183         } catch (RequestValidationException e) {
184             response = processError(ApplicationMsgs.PROCESS_REQUEST_ERROR, Status.BAD_REQUEST, //
185                     e, e.getLocalizedMessage());
186         } finally {
187             applicationLogger.debug(stopwatch + LogHelper.getCallerMethodName(0));
188         }
189
190         return response;
191     }
192
193     private Response processError(ApplicationMsgs applicationMsgs, Status responseStatus, Exception e, String message) {
194         applicationLogger.setContextValue(MdcParameter.RESPONSE_CODE, String.valueOf(responseStatus.getStatusCode()));
195         applicationLogger.setContextValue(MdcParameter.RESPONSE_DESCRIPTION, responseStatus.getReasonPhrase());
196         applicationLogger.error(applicationMsgs, e);
197         return buildResponse(responseStatus, message);
198     }
199
200     /**
201      * Helper method to create a REST response object.
202      *
203      * @param status
204      *            response status code
205      * @param entity
206      *            response payload
207      * @return
208      */
209     private Response buildResponse(Status status, String entity) {
210         return Response.status(status).entity(entity).type(MediaType.APPLICATION_JSON).build();
211     }
212 }