17d0b65fb7ecda975808b7d1cc043baa58ca767a
[aai/babel.git] / src / main / java / org / onap / aai / babel / service / GenerateArtifactsServiceImpl.java
1 /**
2  * ============LICENSE_START=======================================================
3  * org.onap.aai
4  * ================================================================================
5  * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
6  * Copyright © 2017-2018 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 package org.onap.aai.babel.service;
22
23 import com.google.gson.Gson;
24 import com.google.gson.GsonBuilder;
25 import com.google.gson.JsonSyntaxException;
26 import java.util.Base64;
27 import java.util.List;
28 import java.util.UUID;
29 import javax.inject.Inject;
30 import javax.servlet.http.HttpServletRequest;
31 import javax.ws.rs.core.HttpHeaders;
32 import javax.ws.rs.core.MediaType;
33 import javax.ws.rs.core.Response;
34 import javax.ws.rs.core.Response.Status;
35 import javax.ws.rs.core.UriInfo;
36 import org.apache.commons.lang3.time.StopWatch;
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
53 /** Generate SDC Artifacts by passing in a CSAR payload, Artifact Name and Artifact version */
54 public class GenerateArtifactsServiceImpl implements GenerateArtifactsService {
55     private static final LogHelper applicationLogger = LogHelper.INSTANCE;
56
57     private AAIMicroServiceAuth aaiMicroServiceAuth;
58
59     /** @param authorization */
60     @Inject
61     public GenerateArtifactsServiceImpl(final AAIMicroServiceAuth authorization) {
62         this.aaiMicroServiceAuth = authorization;
63     }
64
65     /*
66      * (non-Javadoc)
67      *
68      * @see org.onap.aai.babel.service.GenerateArtifactsService#generateArtifacts(javax.ws.rs.core.UriInfo,
69      * javax.ws.rs.core.HttpHeaders, javax.servlet.http.HttpServletRequest, java.lang.String)
70      */
71     @Override
72     public Response generateArtifacts(UriInfo uriInfo, HttpHeaders headers, HttpServletRequest servletRequest,
73             String requestBody) {
74         applicationLogger.startAudit(headers, servletRequest);
75         applicationLogger.info(ApplicationMsgs.BABEL_REQUEST_PAYLOAD,
76                 "Received request: " + headers.getRequestHeaders() + requestBody);
77         applicationLogger.debug(String.format(
78                 "Received request. UriInfo \"%s\", HttpHeaders \"%s\", ServletRequest \"%s\", Request \"%s\"", uriInfo,
79                 headers, servletRequest, requestBody));
80
81         // Additional name/value pairs according to EELF guidelines
82         applicationLogger.setContextValue("Protocol", "https");
83         applicationLogger.setContextValue("Method", "POST");
84         applicationLogger.setContextValue("Path", uriInfo.getPath());
85         applicationLogger.setContextValue("Query", uriInfo.getPathParameters().toString());
86
87         RequestHeaders requestHeaders = new RequestHeaders(headers);
88         applicationLogger.info(ApplicationMsgs.BABEL_REQUEST_PAYLOAD, requestHeaders.toString());
89
90         String requestId = requestHeaders.getCorrelationId();
91         if (requestId == null) {
92             requestId = UUID.randomUUID().toString();
93             applicationLogger.info(ApplicationMsgs.MISSING_REQUEST_ID, requestId);
94             applicationLogger.setContextValue(MdcParameter.REQUEST_ID, requestId);
95         }
96
97         Response response;
98         try {
99             boolean authorized = aaiMicroServiceAuth.validateRequest(headers, servletRequest,
100                     AAIMicroServiceAuthCore.HTTP_METHODS.POST, uriInfo.getPath(false));
101
102             response = authorized ? generateArtifacts(requestBody)
103                     : buildResponse(Status.UNAUTHORIZED, "User not authorized to perform the operation.");
104         } catch (Exception e) {
105             applicationLogger.error(ApplicationMsgs.PROCESS_REQUEST_ERROR, e);
106             applicationLogger.logAuditError(e);
107             return buildResponse(Status.INTERNAL_SERVER_ERROR,
108                     "Error while processing request. Please check the babel service logs for more details.\n");
109         }
110
111         StatusCode statusDescription;
112         int statusCode = response.getStatus();
113         if (statusCode / 100 == 2) {
114             statusDescription = StatusCode.COMPLETE;
115         } else {
116             statusDescription = StatusCode.ERROR;
117         }
118         applicationLogger.logAudit(statusDescription, Integer.toString(statusCode),
119                 Response.Status.fromStatusCode(statusCode).getReasonPhrase(), response.getEntity().toString());
120
121         return response;
122     }
123
124     /**
125      * Generate XML model artifacts from request body.
126      *
127      * @param requestBody the request body in JSON format
128      * @return response object containing the generated XML models
129      */
130     protected Response generateArtifacts(String requestBody) {
131         StopWatch stopwatch = new StopWatch();
132         stopwatch.start();
133
134         Response response;
135
136         try {
137             Gson gson = new GsonBuilder().disableHtmlEscaping().create();
138
139             BabelRequest babelRequest = gson.fromJson(requestBody, BabelRequest.class);
140             RequestValidator.validateRequest(babelRequest);
141             byte[] csarFile = Base64.getDecoder().decode(babelRequest.getCsar());
142
143             List<BabelArtifact> babelArtifacts = new CsarToXmlConverter().generateXmlFromCsar(csarFile,
144                     babelRequest.getArtifactName(), babelRequest.getArtifactVersion());
145
146             BabelArtifact vendorImageConfiguration = new VnfVendorImageExtractor().extract(csarFile);
147             if (vendorImageConfiguration != null) {
148                 babelArtifacts.add(vendorImageConfiguration);
149             }
150
151             response = buildResponse(Status.OK, gson.toJson(babelArtifacts));
152         } catch (JsonSyntaxException e) {
153             response = processError(ApplicationMsgs.INVALID_REQUEST_JSON, Status.BAD_REQUEST, e, "Malformed request.");
154         } catch (CsarConverterException e) {
155             response = processError(ApplicationMsgs.INVALID_CSAR_FILE, Status.INTERNAL_SERVER_ERROR, e,
156                     "Error converting CSAR artifact to XML model.");
157         } catch (ToscaToCatalogException e) {
158             response = processError(ApplicationMsgs.PROCESSING_VNF_CATALOG_ERROR, Status.INTERNAL_SERVER_ERROR, e,
159                     "Error converting CSAR artifact to VNF catalog.");
160         } catch (RequestValidationException e) {
161             response =
162                     processError(ApplicationMsgs.PROCESS_REQUEST_ERROR, Status.BAD_REQUEST, e, e.getLocalizedMessage());
163         } catch (Exception e) {
164             response = processError(ApplicationMsgs.PROCESS_REQUEST_ERROR, Status.INTERNAL_SERVER_ERROR, e,
165                     "Error while processing request. Please check the babel service logs for more details.\n");
166         } finally {
167             applicationLogger.logMetrics(stopwatch, LogHelper.getCallerMethodName(0));
168         }
169
170         return response;
171     }
172
173     private Response processError(ApplicationMsgs applicationMsgs, Status responseStatus, Exception e, String message) {
174         applicationLogger.error(applicationMsgs, e);
175
176         return buildResponse(responseStatus, message);
177     }
178
179     /**
180      * Helper method to create a REST response object.
181      *
182      * @param status response status code
183      * @param entity response payload
184      * @return
185      */
186     private Response buildResponse(Status status, String entity) {
187     // @formatter:off
188     return Response.status(status).entity(entity).type(MediaType.TEXT_PLAIN).build();
189     // @formatter:on
190     }
191 }