2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (c) 2017-2019 AT&T Intellectual Property. All rights reserved.
6 * Copyright (c) 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.AAIAuthException;
40 import org.onap.aai.auth.AAIMicroServiceAuth;
41 import org.onap.aai.auth.AAIMicroServiceAuthCore;
42 import org.onap.aai.babel.csar.CsarConverterException;
43 import org.onap.aai.babel.csar.CsarToXmlConverter;
44 import org.onap.aai.babel.csar.vnfcatalog.ToscaToCatalogException;
45 import org.onap.aai.babel.csar.vnfcatalog.VnfVendorImageExtractor;
46 import org.onap.aai.babel.logging.ApplicationMsgs;
47 import org.onap.aai.babel.logging.LogHelper;
48 import org.onap.aai.babel.logging.LogHelper.MdcParameter;
49 import org.onap.aai.babel.logging.LogHelper.StatusCode;
50 import org.onap.aai.babel.request.RequestHeaders;
51 import org.onap.aai.babel.service.data.BabelArtifact;
52 import org.onap.aai.babel.service.data.BabelRequest;
53 import org.onap.aai.babel.util.RequestValidationException;
54 import org.onap.aai.babel.util.RequestValidator;
55 import org.springframework.stereotype.Service;
58 * Generate SDC Artifacts by passing in a CSAR payload, Artifact Name and Artifact version.
62 public class GenerateArtifactsServiceImpl implements GenerateArtifactsService {
63 private static final LogHelper applicationLogger = LogHelper.INSTANCE;
65 private AAIMicroServiceAuth aaiMicroServiceAuth;
68 * @param authorization
72 public GenerateArtifactsServiceImpl(final AAIMicroServiceAuth authorization) {
73 this.aaiMicroServiceAuth = authorization;
79 * @see org.onap.aai.babel.service.GenerateArtifactsService#generateArtifacts(javax.ws.rs.core.UriInfo,
80 * javax.ws.rs.core.HttpHeaders, javax.servlet.http.HttpServletRequest, java.lang.String)
83 public Response generateArtifacts(UriInfo uriInfo, HttpHeaders headers, HttpServletRequest servletRequest,
85 applicationLogger.startAudit(headers, servletRequest);
86 applicationLogger.info(ApplicationMsgs.BABEL_REQUEST_PAYLOAD,
87 "Received request: " + headers.getRequestHeaders() + requestBody);
88 applicationLogger.debug(String.format(
89 "Received request. UriInfo \"%s\", HttpHeaders \"%s\", ServletRequest \"%s\", Request \"%s\"", uriInfo,
90 headers, servletRequest, requestBody));
92 // Additional name/value pairs according to EELF guidelines
93 applicationLogger.setContextValue("Protocol", "https");
94 applicationLogger.setContextValue("Method", "POST");
95 applicationLogger.setContextValue("Path", uriInfo.getPath());
96 applicationLogger.setContextValue("Query", uriInfo.getPathParameters().toString());
98 RequestHeaders requestHeaders = new RequestHeaders(headers);
99 applicationLogger.info(ApplicationMsgs.BABEL_REQUEST_PAYLOAD, requestHeaders.toString());
101 String requestId = requestHeaders.getCorrelationId();
102 if (requestId == null) {
103 requestId = UUID.randomUUID().toString();
104 applicationLogger.info(ApplicationMsgs.MISSING_REQUEST_ID, requestId);
105 applicationLogger.setContextValue(MdcParameter.REQUEST_ID, requestId);
110 // Get last URI path segment to use for authentication
111 List<PathSegment> pathSegments = uriInfo.getPathSegments();
112 String lastPathSegment = pathSegments.isEmpty() ? "" : pathSegments.get(pathSegments.size() - 1).getPath();
114 boolean authorized = aaiMicroServiceAuth.validateRequest(headers, servletRequest,
115 AAIMicroServiceAuthCore.HTTP_METHODS.POST, lastPathSegment);
117 response = authorized ? generateArtifacts(requestBody)
118 : buildResponse(Status.UNAUTHORIZED, "User not authorized to perform the operation.");
119 } catch (AAIAuthException e) {
120 applicationLogger.error(ApplicationMsgs.PROCESS_REQUEST_ERROR, e);
121 applicationLogger.logAuditError(e);
122 return buildResponse(Status.INTERNAL_SERVER_ERROR,
123 "Error while processing request. Please check the Babel service logs for more details.\n");
126 StatusCode statusDescription;
127 int statusCode = response.getStatus();
128 if (statusCode / 100 == 2) {
129 statusDescription = StatusCode.COMPLETE;
131 statusDescription = StatusCode.ERROR;
133 applicationLogger.logAudit(statusDescription, Integer.toString(statusCode),
134 Response.Status.fromStatusCode(statusCode).getReasonPhrase(), response.getEntity().toString());
140 * Generate XML model artifacts from request body.
143 * the request body in JSON format
144 * @return response object containing the generated XML models
146 protected Response generateArtifacts(String requestBody) {
147 StopWatch stopwatch = new StopWatch();
153 Gson gson = new GsonBuilder().disableHtmlEscaping().create();
155 BabelRequest babelRequest = gson.fromJson(requestBody, BabelRequest.class);
156 new RequestValidator().validateRequest(babelRequest);
157 byte[] csarFile = Base64.getDecoder().decode(babelRequest.getCsar());
159 List<BabelArtifact> babelArtifacts = new CsarToXmlConverter().generateXmlFromCsar(csarFile,
160 babelRequest.getArtifactName(), babelRequest.getArtifactVersion());
162 BabelArtifact vendorImageConfiguration = new VnfVendorImageExtractor().extract(csarFile);
163 if (vendorImageConfiguration != null) {
164 babelArtifacts.add(vendorImageConfiguration);
167 response = buildResponse(Status.OK, gson.toJson(babelArtifacts));
168 } catch (JsonSyntaxException e) {
169 response = processError(ApplicationMsgs.INVALID_REQUEST_JSON, Status.BAD_REQUEST, e, "Malformed request.");
170 } catch (CsarConverterException e) {
171 response = processError(ApplicationMsgs.INVALID_CSAR_FILE, Status.INTERNAL_SERVER_ERROR, e,
172 "Error converting CSAR artifact to XML model.");
173 } catch (ToscaToCatalogException e) {
174 response = processError(ApplicationMsgs.PROCESSING_VNF_CATALOG_ERROR, Status.INTERNAL_SERVER_ERROR, e,
175 "Error converting CSAR artifact to VNF catalog.");
176 } catch (RequestValidationException e) {
177 response = processError(ApplicationMsgs.PROCESS_REQUEST_ERROR, Status.BAD_REQUEST, //
178 e, e.getLocalizedMessage());
180 applicationLogger.logMetrics(stopwatch, LogHelper.getCallerMethodName(0));
186 private Response processError(ApplicationMsgs applicationMsgs, Status responseStatus, Exception e, String message) {
187 applicationLogger.error(applicationMsgs, e);
189 return buildResponse(responseStatus, message);
193 * Helper method to create a REST response object.
196 * response status code
201 private Response buildResponse(Status status, String entity) {
202 return Response.status(status).entity(entity).type(MediaType.TEXT_PLAIN).build();