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