Updated pom to remove distribution-management section and corrected aai base image...
[aai/babel.git] / src / main / java / org / onap / aai / babel / service / GenerateArtifactsServiceImpl.java
index 17d0b65..4fac909 100644 (file)
@@ -1,9 +1,9 @@
 /**
- * ============LICENSE_START=======================================================
+ * ============LICENSE_START=======================================================
  * org.onap.aai
  * ================================================================================
- * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
- * Copyright © 2017-2018 European Software Marketing Ltd.
+ * Copyright (c) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (c) 2017-2019 European Software Marketing Ltd.
  * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -18,6 +18,7 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
+
 package org.onap.aai.babel.service;
 
 import com.google.gson.Gson;
@@ -28,12 +29,11 @@ import java.util.List;
 import java.util.UUID;
 import javax.inject.Inject;
 import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.core.HttpHeaders;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
+import javax.ws.rs.core.*;
 import javax.ws.rs.core.Response.Status;
-import javax.ws.rs.core.UriInfo;
+
 import org.apache.commons.lang3.time.StopWatch;
+import org.onap.aai.auth.AAIAuthException;
 import org.onap.aai.auth.AAIMicroServiceAuth;
 import org.onap.aai.auth.AAIMicroServiceAuthCore;
 import org.onap.aai.babel.csar.CsarConverterException;
@@ -49,14 +49,22 @@ import org.onap.aai.babel.service.data.BabelArtifact;
 import org.onap.aai.babel.service.data.BabelRequest;
 import org.onap.aai.babel.util.RequestValidationException;
 import org.onap.aai.babel.util.RequestValidator;
+import org.springframework.stereotype.Service;
 
-/** Generate SDC Artifacts by passing in a CSAR payload, Artifact Name and Artifact version */
+/**
+ * Generate SDC Artifacts by passing in a CSAR payload, Artifact Name and Artifact version.
+ *
+ */
+@Service
 public class GenerateArtifactsServiceImpl implements GenerateArtifactsService {
     private static final LogHelper applicationLogger = LogHelper.INSTANCE;
 
     private AAIMicroServiceAuth aaiMicroServiceAuth;
 
-    /** @param authorization */
+    /**
+     * @param authorization
+     *            the auth module
+     */
     @Inject
     public GenerateArtifactsServiceImpl(final AAIMicroServiceAuth authorization) {
         this.aaiMicroServiceAuth = authorization;
@@ -88,7 +96,7 @@ public class GenerateArtifactsServiceImpl implements GenerateArtifactsService {
         applicationLogger.info(ApplicationMsgs.BABEL_REQUEST_PAYLOAD, requestHeaders.toString());
 
         String requestId = requestHeaders.getCorrelationId();
-        if (requestId == null) {
+        if (requestId == null || !isRequestIDValid(requestId)) {
             requestId = UUID.randomUUID().toString();
             applicationLogger.info(ApplicationMsgs.MISSING_REQUEST_ID, requestId);
             applicationLogger.setContextValue(MdcParameter.REQUEST_ID, requestId);
@@ -96,16 +104,20 @@ public class GenerateArtifactsServiceImpl implements GenerateArtifactsService {
 
         Response response;
         try {
+            // Get last URI path segment to use for authentication
+            List<PathSegment> pathSegments = uriInfo.getPathSegments();
+            String lastPathSegment = pathSegments.isEmpty() ? "" : pathSegments.get(pathSegments.size() - 1).getPath();
+
             boolean authorized = aaiMicroServiceAuth.validateRequest(headers, servletRequest,
-                    AAIMicroServiceAuthCore.HTTP_METHODS.POST, uriInfo.getPath(false));
+                    AAIMicroServiceAuthCore.HTTP_METHODS.POST, lastPathSegment);
 
             response = authorized ? generateArtifacts(requestBody)
                     : buildResponse(Status.UNAUTHORIZED, "User not authorized to perform the operation.");
-        } catch (Exception e) {
+        } catch (AAIAuthException e) {
             applicationLogger.error(ApplicationMsgs.PROCESS_REQUEST_ERROR, e);
             applicationLogger.logAuditError(e);
             return buildResponse(Status.INTERNAL_SERVER_ERROR,
-                    "Error while processing request. Please check the babel service logs for more details.\n");
+                    "Error while processing request. Please check the Babel service logs for more details.\n");
         }
 
         StatusCode statusDescription;
@@ -121,10 +133,20 @@ public class GenerateArtifactsServiceImpl implements GenerateArtifactsService {
         return response;
     }
 
+    private boolean isRequestIDValid(String requestId) {
+        try {
+            UUID.fromString(requestId);
+        } catch (IllegalArgumentException e) {
+            return false;
+        }
+        return true;
+    }
+
     /**
      * Generate XML model artifacts from request body.
      *
-     * @param requestBody the request body in JSON format
+     * @param requestBody
+     *            the request body in JSON format
      * @return response object containing the generated XML models
      */
     protected Response generateArtifacts(String requestBody) {
@@ -137,7 +159,7 @@ public class GenerateArtifactsServiceImpl implements GenerateArtifactsService {
             Gson gson = new GsonBuilder().disableHtmlEscaping().create();
 
             BabelRequest babelRequest = gson.fromJson(requestBody, BabelRequest.class);
-            RequestValidator.validateRequest(babelRequest);
+            new RequestValidator().validateRequest(babelRequest);
             byte[] csarFile = Base64.getDecoder().decode(babelRequest.getCsar());
 
             List<BabelArtifact> babelArtifacts = new CsarToXmlConverter().generateXmlFromCsar(csarFile,
@@ -149,6 +171,7 @@ public class GenerateArtifactsServiceImpl implements GenerateArtifactsService {
             }
 
             response = buildResponse(Status.OK, gson.toJson(babelArtifacts));
+            applicationLogger.info(ApplicationMsgs.DISTRIBUTION_EVENT,LogHelper.getCallerMethodName(0));
         } catch (JsonSyntaxException e) {
             response = processError(ApplicationMsgs.INVALID_REQUEST_JSON, Status.BAD_REQUEST, e, "Malformed request.");
         } catch (CsarConverterException e) {
@@ -158,34 +181,32 @@ public class GenerateArtifactsServiceImpl implements GenerateArtifactsService {
             response = processError(ApplicationMsgs.PROCESSING_VNF_CATALOG_ERROR, Status.INTERNAL_SERVER_ERROR, e,
                     "Error converting CSAR artifact to VNF catalog.");
         } catch (RequestValidationException e) {
-            response =
-                    processError(ApplicationMsgs.PROCESS_REQUEST_ERROR, Status.BAD_REQUEST, e, e.getLocalizedMessage());
-        } catch (Exception e) {
-            response = processError(ApplicationMsgs.PROCESS_REQUEST_ERROR, Status.INTERNAL_SERVER_ERROR, e,
-                    "Error while processing request. Please check the babel service logs for more details.\n");
+            response = processError(ApplicationMsgs.PROCESS_REQUEST_ERROR, Status.BAD_REQUEST, //
+                    e, e.getLocalizedMessage());
         } finally {
-            applicationLogger.logMetrics(stopwatch, LogHelper.getCallerMethodName(0));
+            applicationLogger.debug(stopwatch + LogHelper.getCallerMethodName(0));
         }
 
         return response;
     }
 
     private Response processError(ApplicationMsgs applicationMsgs, Status responseStatus, Exception e, String message) {
+        applicationLogger.setContextValue(MdcParameter.RESPONSE_CODE, String.valueOf(responseStatus.getStatusCode()));
+        applicationLogger.setContextValue(MdcParameter.RESPONSE_DESCRIPTION, responseStatus.getReasonPhrase());
         applicationLogger.error(applicationMsgs, e);
-
         return buildResponse(responseStatus, message);
     }
 
     /**
      * Helper method to create a REST response object.
      *
-     * @param status response status code
-     * @param entity response payload
+     * @param status
+     *            response status code
+     * @param entity
+     *            response payload
      * @return
      */
     private Response buildResponse(Status status, String entity) {
-    // @formatter:off
-    return Response.status(status).entity(entity).type(MediaType.TEXT_PLAIN).build();
-    // @formatter:on
+        return Response.status(status).entity(entity).type(MediaType.TEXT_PLAIN).build();
     }
 }