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