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