2 * ============LICENSE_START=======================================================
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
12 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
22 package org.onap.aai.babel.service;
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;
56 /** Generate SDC Artifacts by passing in a CSAR payload, Artifact Name and Artifact version */
58 public class GenerateArtifactsServiceImpl implements GenerateArtifactsService {
59 private static final LogHelper applicationLogger = LogHelper.INSTANCE;
61 private AAIMicroServiceAuth aaiMicroServiceAuth;
64 * @param authorization
67 public GenerateArtifactsServiceImpl(final AAIMicroServiceAuth authorization) {
68 this.aaiMicroServiceAuth = authorization;
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)
78 public Response generateArtifacts(UriInfo uriInfo, HttpHeaders headers, HttpServletRequest servletRequest,
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));
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());
93 RequestHeaders requestHeaders = new RequestHeaders(headers);
94 applicationLogger.info(ApplicationMsgs.BABEL_REQUEST_PAYLOAD, requestHeaders.toString());
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);
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();
109 boolean authorized = aaiMicroServiceAuth.validateRequest(headers, servletRequest,
110 AAIMicroServiceAuthCore.HTTP_METHODS.POST, lastPathSegment);
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");
121 StatusCode statusDescription;
122 int statusCode = response.getStatus();
123 if (statusCode / 100 == 2) {
124 statusDescription = StatusCode.COMPLETE;
126 statusDescription = StatusCode.ERROR;
128 applicationLogger.logAudit(statusDescription, Integer.toString(statusCode),
129 Response.Status.fromStatusCode(statusCode).getReasonPhrase(), response.getEntity().toString());
135 * Generate XML model artifacts from request body.
137 * @param requestBody the request body in JSON format
138 * @return response object containing the generated XML models
140 protected Response generateArtifacts(String requestBody) {
141 StopWatch stopwatch = new StopWatch();
147 Gson gson = new GsonBuilder().disableHtmlEscaping().create();
149 BabelRequest babelRequest = gson.fromJson(requestBody, BabelRequest.class);
150 new RequestValidator().validateRequest(babelRequest);
151 byte[] csarFile = Base64.getDecoder().decode(babelRequest.getCsar());
153 List<BabelArtifact> babelArtifacts = new CsarToXmlConverter().generateXmlFromCsar(csarFile,
154 babelRequest.getArtifactName(), babelRequest.getArtifactVersion());
156 BabelArtifact vendorImageConfiguration = new VnfVendorImageExtractor().extract(csarFile);
157 if (vendorImageConfiguration != null) {
158 babelArtifacts.add(vendorImageConfiguration);
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) {
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");
177 applicationLogger.logMetrics(stopwatch, LogHelper.getCallerMethodName(0));
183 private Response processError(ApplicationMsgs applicationMsgs, Status responseStatus, Exception e, String message) {
184 applicationLogger.error(applicationMsgs, e);
186 return buildResponse(responseStatus, message);
190 * Helper method to create a REST response object.
192 * @param status response status code
193 * @param entity response payload
196 private Response buildResponse(Status status, String entity) {
198 return Response.status(status).entity(entity).type(MediaType.TEXT_PLAIN).build();