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.*;
33 import javax.ws.rs.core.Response.Status;
35 import org.apache.commons.lang3.time.StopWatch;
36 import org.onap.aai.auth.AAIAuthException;
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 import org.springframework.stereotype.Service;
55 * Generate SDC Artifacts by passing in a CSAR payload, Artifact Name and Artifact version.
59 public class GenerateArtifactsServiceImpl implements GenerateArtifactsService {
60 private static final LogHelper applicationLogger = LogHelper.INSTANCE;
62 private AAIMicroServiceAuth aaiMicroServiceAuth;
65 * @param authorization
69 public GenerateArtifactsServiceImpl(final AAIMicroServiceAuth authorization) {
70 this.aaiMicroServiceAuth = authorization;
76 * @see org.onap.aai.babel.service.GenerateArtifactsService#generateArtifacts(javax.ws.rs.core.UriInfo,
77 * javax.ws.rs.core.HttpHeaders, javax.servlet.http.HttpServletRequest, java.lang.String)
80 public Response generateArtifacts(UriInfo uriInfo, HttpHeaders headers, HttpServletRequest servletRequest,
82 applicationLogger.startAudit(headers, servletRequest);
83 applicationLogger.info(ApplicationMsgs.BABEL_REQUEST_PAYLOAD,
84 "Received request: " + headers.getRequestHeaders() + requestBody);
85 applicationLogger.debug(String.format(
86 "Received request. UriInfo \"%s\", HttpHeaders \"%s\", ServletRequest \"%s\", Request \"%s\"", uriInfo,
87 headers, servletRequest, requestBody));
89 // Additional name/value pairs according to EELF guidelines
90 applicationLogger.setContextValue("Protocol", "https");
91 applicationLogger.setContextValue("Method", "POST");
92 applicationLogger.setContextValue("Path", uriInfo.getPath());
93 applicationLogger.setContextValue("Query", uriInfo.getPathParameters().toString());
95 RequestHeaders requestHeaders = new RequestHeaders(headers);
96 applicationLogger.info(ApplicationMsgs.BABEL_REQUEST_PAYLOAD, requestHeaders.toString());
98 String requestId = requestHeaders.getCorrelationId();
99 if (requestId == null || !isRequestIDValid(requestId)) {
100 requestId = UUID.randomUUID().toString();
101 applicationLogger.info(ApplicationMsgs.MISSING_REQUEST_ID, requestId);
102 applicationLogger.setContextValue(MdcParameter.REQUEST_ID, requestId);
107 // Get last URI path segment to use for authentication
108 List<PathSegment> pathSegments = uriInfo.getPathSegments();
109 String lastPathSegment = pathSegments.isEmpty() ? "" : pathSegments.get(pathSegments.size() - 1).getPath();
111 boolean authorized = aaiMicroServiceAuth.validateRequest(headers, servletRequest,
112 AAIMicroServiceAuthCore.HTTP_METHODS.POST, lastPathSegment);
114 response = authorized ? generateArtifacts(requestBody)
115 : buildResponse(Status.UNAUTHORIZED, "User not authorized to perform the operation.");
116 } catch (AAIAuthException e) {
117 applicationLogger.error(ApplicationMsgs.PROCESS_REQUEST_ERROR, e);
118 applicationLogger.logAuditError(e);
119 return buildResponse(Status.INTERNAL_SERVER_ERROR,
120 "Error while processing request. Please check the Babel service logs for more details.\n");
123 StatusCode statusDescription;
124 int statusCode = response.getStatus();
125 if (statusCode / 100 == 2) {
126 statusDescription = StatusCode.COMPLETE;
128 statusDescription = StatusCode.ERROR;
130 applicationLogger.logAudit(statusDescription, Integer.toString(statusCode),
131 Response.Status.fromStatusCode(statusCode).getReasonPhrase(), response.getEntity().toString());
136 private boolean isRequestIDValid(String requestId) {
138 UUID.fromString(requestId);
139 } catch (IllegalArgumentException e) {
146 * Generate XML model artifacts from request body.
149 * the request body in JSON format
150 * @return response object containing the generated XML models
152 protected Response generateArtifacts(String requestBody) {
153 StopWatch stopwatch = new StopWatch();
159 Gson gson = new GsonBuilder().disableHtmlEscaping().create();
161 BabelRequest babelRequest = gson.fromJson(requestBody, BabelRequest.class);
162 new RequestValidator().validateRequest(babelRequest);
163 byte[] csarFile = Base64.getDecoder().decode(babelRequest.getCsar());
165 List<BabelArtifact> babelArtifacts = new CsarToXmlConverter().generateXmlFromCsar(csarFile,
166 babelRequest.getArtifactName(), babelRequest.getArtifactVersion());
168 BabelArtifact vendorImageConfiguration = new VnfVendorImageExtractor().extract(csarFile);
169 if (vendorImageConfiguration != null) {
170 babelArtifacts.add(vendorImageConfiguration);
173 response = buildResponse(Status.OK, gson.toJson(babelArtifacts));
174 applicationLogger.info(ApplicationMsgs.DISTRIBUTION_EVENT,LogHelper.getCallerMethodName(0));
175 } catch (JsonSyntaxException e) {
176 response = processError(ApplicationMsgs.INVALID_REQUEST_JSON, Status.BAD_REQUEST, e, "Malformed request.");
177 } catch (CsarConverterException e) {
178 response = processError(ApplicationMsgs.INVALID_CSAR_FILE, Status.INTERNAL_SERVER_ERROR, e,
179 "Error converting CSAR artifact to XML model.");
180 } catch (ToscaToCatalogException e) {
181 response = processError(ApplicationMsgs.PROCESSING_VNF_CATALOG_ERROR, Status.INTERNAL_SERVER_ERROR, e,
182 "Error converting CSAR artifact to VNF catalog.");
183 } catch (RequestValidationException e) {
184 response = processError(ApplicationMsgs.PROCESS_REQUEST_ERROR, Status.BAD_REQUEST, //
185 e, e.getLocalizedMessage());
187 applicationLogger.debug(stopwatch + LogHelper.getCallerMethodName(0));
193 private Response processError(ApplicationMsgs applicationMsgs, Status responseStatus, Exception e, String message) {
194 applicationLogger.setContextValue(MdcParameter.RESPONSE_CODE, String.valueOf(responseStatus.getStatusCode()));
195 applicationLogger.setContextValue(MdcParameter.RESPONSE_DESCRIPTION, responseStatus.getReasonPhrase());
196 applicationLogger.error(applicationMsgs, e);
197 return buildResponse(responseStatus, message);
201 * Helper method to create a REST response object.
204 * response status code
209 private Response buildResponse(Status status, String entity) {
210 return Response.status(status).entity(entity).type(MediaType.TEXT_PLAIN).build();