Service Consumption BE
[sdc.git] / catalog-be / src / main / java / org / openecomp / sdc / be / impl / ComponentsUtils.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.openecomp.sdc.be.impl;
22
23 import com.fasterxml.jackson.databind.DeserializationFeature;
24 import com.fasterxml.jackson.databind.ObjectMapper;
25 import com.fasterxml.jackson.databind.module.SimpleModule;
26 import com.google.gson.Gson;
27 import com.google.gson.GsonBuilder;
28 import com.google.gson.reflect.TypeToken;
29 import fj.data.Either;
30 import org.apache.commons.lang3.StringUtils;
31 import org.openecomp.sdc.be.auditing.api.AuditEventFactory;
32 import org.openecomp.sdc.be.auditing.impl.*;
33 import org.openecomp.sdc.be.auditing.impl.category.AuditCategoryEventFactory;
34 import org.openecomp.sdc.be.auditing.impl.category.AuditGetCategoryHierarchyEventFactory;
35 import org.openecomp.sdc.be.auditing.impl.distribution.*;
36 import org.openecomp.sdc.be.auditing.impl.externalapi.*;
37 import org.openecomp.sdc.be.auditing.impl.resourceadmin.AuditResourceEventFactoryManager;
38 import org.openecomp.sdc.be.auditing.impl.usersadmin.AuditGetUsersListEventFactory;
39 import org.openecomp.sdc.be.auditing.impl.usersadmin.AuditUserAccessEventFactory;
40 import org.openecomp.sdc.be.auditing.impl.usersadmin.AuditUserAdminEventFactory;
41 import org.openecomp.sdc.be.components.impl.ImportUtils;
42 import org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum;
43 import org.openecomp.sdc.be.components.impl.ResponseFormatManager;
44 import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
45 import org.openecomp.sdc.be.config.BeEcompErrorManager;
46 import org.openecomp.sdc.be.dao.api.ActionStatus;
47 import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus;
48 import org.openecomp.sdc.be.dao.graph.datatype.AdditionalInformationEnum;
49 import org.openecomp.sdc.be.datatypes.elements.AdditionalInfoParameterInfo;
50 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
51 import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
52 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
53 import org.openecomp.sdc.be.model.*;
54 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
55 import org.openecomp.sdc.be.model.operations.impl.PropertyOperation.PropertyConstraintDeserialiser;
56 import org.openecomp.sdc.be.model.operations.impl.PropertyOperation.PropertyConstraintJacksonDeserializer;
57 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
58 import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants;
59 import org.openecomp.sdc.be.resources.data.auditing.model.*;
60 import org.openecomp.sdc.be.tosca.ToscaError;
61 import org.openecomp.sdc.common.api.Constants;
62 import org.openecomp.sdc.common.log.wrappers.Logger;
63 import org.openecomp.sdc.common.util.ThreadLocalsHolder;
64 import org.openecomp.sdc.common.util.ValidationUtils;
65 import org.openecomp.sdc.exception.ResponseFormat;
66
67 import javax.servlet.http.HttpServletRequest;
68 import java.lang.reflect.Type;
69 import java.util.Collections;
70 import java.util.List;
71
72 @org.springframework.stereotype.Component("componentUtils")
73 public class ComponentsUtils {
74
75     private static final String CONVERT_STORAGE_RESPONSE_TO_ACTION_RESPONSE = "convert storage response {} to action response {}";
76         private static final String INSIDE_AUDITING_FOR_AUDIT_ACTION = "Inside auditing for audit action {}";
77         private static final String AUDIT_BEFORE_SENDING_RESPONSE = "audit before sending response";
78         private static final String CONVERT_JSON_TO_OBJECT = "convertJsonToObject";
79         private static final Logger log = Logger.getLogger(ComponentsUtils.class);
80     private final AuditingManager auditingManager;
81     private final ResponseFormatManager responseFormatManager;
82
83     public ComponentsUtils(AuditingManager auditingManager) {
84         this.auditingManager = auditingManager;
85         this.responseFormatManager = ResponseFormatManager.getInstance();
86     }
87
88     public AuditingManager getAuditingManager() {
89         return auditingManager;
90     }
91
92     public <T> Either<T, ResponseFormat> convertJsonToObject(String data, User user, Class<T> clazz, AuditingActionEnum actionEnum) {
93         if (data == null) {
94             BeEcompErrorManager.getInstance().logBeInvalidJsonInput(CONVERT_JSON_TO_OBJECT);
95             log.debug("object is null after converting from json");
96             ResponseFormat responseFormat = getInvalidContentErrorAndAudit(user, actionEnum);
97             return Either.right(responseFormat);
98         }
99         try {
100             T obj = parseJsonToObject(data, clazz);
101             return Either.left(obj);
102         } catch (Exception e) {
103             // INVALID JSON
104             BeEcompErrorManager.getInstance().logBeInvalidJsonInput(CONVERT_JSON_TO_OBJECT);
105             log.debug("failed to convert from json {}", data, e);
106             ResponseFormat responseFormat = getInvalidContentErrorAndAudit(user, actionEnum);
107             return Either.right(responseFormat);
108         }
109     }
110
111     public static <T> T parseJsonToObject(String data, Class<T> clazz) {
112         Type constraintType = new TypeToken<PropertyConstraint>() {}.getType();
113         Gson gson = new GsonBuilder().registerTypeAdapter(constraintType, new PropertyConstraintDeserialiser()).create();
114         log.trace("convert json to object. json=\n{}", data);
115         return gson.fromJson(data, clazz);
116     }
117
118     public <T> Either<T, ResponseFormat> convertJsonToObjectUsingObjectMapper(String data, User user, Class<T> clazz, AuditingActionEnum actionEnum, ComponentTypeEnum typeEnum) {
119         T component = null;
120         ObjectMapper mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
121         mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
122         try {
123             log.trace("convert json to object. json=\n{}", data);
124
125             SimpleModule module = new SimpleModule("customDeserializationModule");
126             module.addDeserializer(PropertyConstraint.class, new PropertyConstraintJacksonDeserializer());
127             mapper.registerModule(module);
128
129             component = mapper.readValue(data, clazz);
130             if (component == null) {
131                 BeEcompErrorManager.getInstance().logBeInvalidJsonInput(CONVERT_JSON_TO_OBJECT);
132                 log.debug("object is null after converting from json");
133                 ResponseFormat responseFormat = getInvalidContentErrorAndAuditComponent(user, actionEnum, typeEnum);
134                 return Either.right(responseFormat);
135             }
136         } catch (Exception e) {
137             BeEcompErrorManager.getInstance().logBeInvalidJsonInput(CONVERT_JSON_TO_OBJECT);
138             log.debug("failed to convert from json {}", data, e);
139             ResponseFormat responseFormat = getInvalidContentErrorAndAuditComponent(user, actionEnum, typeEnum);
140             return Either.right(responseFormat);
141         }
142         return Either.left(component);
143     }
144
145     public ResponseFormat getResponseFormat(ActionStatus actionStatus, String... params) {
146         return responseFormatManager.getResponseFormat(actionStatus, params);
147     }
148    
149     public ResponseFormat getResponseFormat(StorageOperationStatus storageStatus, String... params) {
150         return responseFormatManager.getResponseFormat(this.convertFromStorageResponse(storageStatus), params);
151     }
152
153     public <T> Either<List<T>, ResponseFormat> convertToResponseFormatOrNotFoundErrorToEmptyList(StorageOperationStatus storageOperationStatus) {
154         return storageOperationStatus.equals(StorageOperationStatus.NOT_FOUND) ? Either.left(Collections.emptyList()) :
155                                                                                  Either.right(getResponseFormat(storageOperationStatus));
156     }
157
158     /**
159      * Returns the response format of resource error with respective variables according to actionStatus. This is needed for cases where actionStatus is anonymously converted from storage operation, and the caller doesn't know what actionStatus he
160      * received. It's caller's Responsibility to fill the resource object passed to this function with needed fields.
161      * <p>
162      * Note that RESOURCE_IN_USE case passes hardcoded "resource" string to the error parameter. This means that if Resource object will also be used for Service, this code needs to be refactored and we should tell Resource from Service.
163      *
164      * @param actionStatus
165      * @param resource
166      * @return
167      */
168     public ResponseFormat getResponseFormatByResource(ActionStatus actionStatus, Resource resource) {
169         if (resource == null) {
170             return getResponseFormat(actionStatus);
171         }
172         ResponseFormat responseFormat;
173
174         switch (actionStatus) {
175             case COMPONENT_VERSION_ALREADY_EXIST:
176                 responseFormat = getResponseFormat(ActionStatus.COMPONENT_VERSION_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(), resource.getVersion());
177                 break;
178             case RESOURCE_NOT_FOUND:
179                 responseFormat = getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resource.getName());
180                 break;
181             case COMPONENT_NAME_ALREADY_EXIST:
182                 responseFormat = getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
183                 break;
184             case COMPONENT_IN_USE:
185                 responseFormat = getResponseFormat(ActionStatus.COMPONENT_IN_USE, ComponentTypeEnum.RESOURCE.name().toLowerCase(), resource.getUniqueId());
186                 break;
187             default:
188                 responseFormat = getResponseFormat(actionStatus);
189                 break;
190         }
191         return responseFormat;
192     }
193
194     public ResponseFormat getResponseFormatByResource(ActionStatus actionStatus, String resourceName) {
195         if (resourceName == null) {
196             return getResponseFormat(actionStatus);
197         }
198
199         ResponseFormat responseFormat;
200         if (actionStatus == ActionStatus.RESOURCE_NOT_FOUND) {
201             responseFormat = getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceName);
202         }
203         else {
204             responseFormat = getResponseFormat(actionStatus);
205         }
206         return responseFormat;
207     }
208
209     public ResponseFormat getResponseFormatByCapabilityType(ActionStatus actionStatus, CapabilityTypeDefinition capabilityType) {
210         if (capabilityType == null) {
211             return getResponseFormat(actionStatus);
212         }
213
214         ResponseFormat responseFormat;
215         if (actionStatus == ActionStatus.CAPABILITY_TYPE_ALREADY_EXIST) {
216             responseFormat = getResponseFormat(ActionStatus.CAPABILITY_TYPE_ALREADY_EXIST, capabilityType.getType());
217         }
218         else {
219             responseFormat = getResponseFormat(actionStatus);
220         }
221         return responseFormat;
222     }
223
224     public <T> ResponseFormat getResponseFormatByElement(ActionStatus actionStatus, T obj) {
225         if (obj == null) {
226             return getResponseFormat(actionStatus);
227         }
228
229         ResponseFormat responseFormat = null;
230         if (actionStatus == ActionStatus.MISSING_CAPABILITY_TYPE) {
231             if (obj instanceof List && org.apache.commons.collections.CollectionUtils.isNotEmpty((List) obj)) {
232                 List list = (List) obj;
233                 if (list.get(0) instanceof RequirementDefinition) {
234                     responseFormat = getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, ((RequirementDefinition) list
235                             .get(0)).getName());    //Arbitray index, all we need is single object
236                     return responseFormat;
237                 }
238             }
239             log.debug("UNKNOWN TYPE : expecting obj as a non empty List<RequirmentsDefinitions>");
240         }
241         else {
242             responseFormat = getResponseFormat(actionStatus);
243         }
244         return responseFormat;
245     }
246
247     /**
248      * Returns the response format of resource error with respective variables according to actionStatus. This is needed for cases where actionStatus is anynomously converted from storage operation, and the caller doesn't know what actionStatus he
249      * received. It's caller's responisibility to fill the passed resource object with needed fields.
250      *
251      * @param actionStatus
252      * @param user
253      * @return
254      */
255     public ResponseFormat getResponseFormatByUser(ActionStatus actionStatus, User user) {
256         if (user == null) {
257             return getResponseFormat(actionStatus);
258         }
259         ResponseFormat requestErrorWrapper;
260         switch (actionStatus) {
261             case INVALID_USER_ID:
262                 requestErrorWrapper = getResponseFormat(actionStatus, user.getUserId());
263                 break;
264             case INVALID_EMAIL_ADDRESS:
265                 requestErrorWrapper = getResponseFormat(actionStatus, user.getEmail());
266                 break;
267             case INVALID_ROLE:
268                 requestErrorWrapper = getResponseFormat(actionStatus, user.getRole());
269                 break;
270             case USER_NOT_FOUND:
271             case USER_ALREADY_EXIST:
272             case USER_INACTIVE:
273             case USER_HAS_ACTIVE_ELEMENTS:
274                 requestErrorWrapper = getResponseFormat(actionStatus, user.getUserId());
275                 break;
276             default:
277                 requestErrorWrapper = getResponseFormat(actionStatus);
278                 break;
279         }
280         return requestErrorWrapper;
281     }
282
283     public ResponseFormat getResponseFormatByUserId(ActionStatus actionStatus, String userId) {
284         User user = new User();
285         user.setUserId(userId);
286         return getResponseFormatByUser(actionStatus, user);
287     }
288
289     public ResponseFormat getResponseFormatByDE(ActionStatus actionStatus, String envName) {
290         ResponseFormat responseFormat;
291
292         switch (actionStatus) {
293             case DISTRIBUTION_ENVIRONMENT_NOT_AVAILABLE:
294                 responseFormat = getResponseFormat(ActionStatus.DISTRIBUTION_ENVIRONMENT_NOT_AVAILABLE, envName);
295                 break;
296             case DISTRIBUTION_ENVIRONMENT_NOT_FOUND:
297                 responseFormat = getResponseFormat(ActionStatus.DISTRIBUTION_ENVIRONMENT_NOT_FOUND, envName);
298                 break;
299             default:
300                 responseFormat = getResponseFormat(actionStatus);
301                 break;
302         }
303         return responseFormat;
304     }
305
306     public ResponseFormat getResponseFormatByArtifactId(ActionStatus actionStatus, String artifactId) {
307         ResponseFormat responseFormat;
308
309         switch (actionStatus) {
310             case RESOURCE_NOT_FOUND:
311             case ARTIFACT_NOT_FOUND:
312                 responseFormat = getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactId);
313                 break;
314             default:
315                 responseFormat = getResponseFormat(actionStatus);
316                 break;
317         }
318         return responseFormat;
319     }
320
321     public ResponseFormat getInvalidContentErrorAndAudit(User user, String resourceName, AuditingActionEnum actionEnum) {
322         ResponseFormat responseFormat = responseFormatManager.getResponseFormat(ActionStatus.INVALID_CONTENT);
323         log.debug(AUDIT_BEFORE_SENDING_RESPONSE);
324         auditResource(responseFormat, user, resourceName, actionEnum);
325         return responseFormat;
326     }
327
328     public ResponseFormat getInvalidContentErrorForConsumerAndAudit(User user, ConsumerDefinition consumer, AuditingActionEnum actionEnum) {
329         ResponseFormat responseFormat = responseFormatManager.getResponseFormat(ActionStatus.INVALID_CONTENT);
330         log.debug(AUDIT_BEFORE_SENDING_RESPONSE);
331         auditConsumerCredentialsEvent(actionEnum, consumer, responseFormat, user);
332         return responseFormat;
333     }
334
335     public ResponseFormat getInvalidContentErrorAndAudit(User user, AuditingActionEnum actionEnum) {
336         ResponseFormat responseFormat = responseFormatManager.getResponseFormat(ActionStatus.INVALID_CONTENT);
337         log.debug(AUDIT_BEFORE_SENDING_RESPONSE);
338         auditAdminUserAction(actionEnum, user, null, null, responseFormat);
339         return responseFormat;
340     }
341
342     public ResponseFormat getInvalidContentErrorAndAuditComponent(User user, AuditingActionEnum actionEnum, ComponentTypeEnum typeEnum) {
343         ResponseFormat responseFormat = responseFormatManager.getResponseFormat(ActionStatus.INVALID_CONTENT);
344         log.debug(AUDIT_BEFORE_SENDING_RESPONSE);
345         auditComponentAdmin(responseFormat, user, null,  actionEnum, typeEnum);
346         return responseFormat;
347     }
348
349     public void auditResource(ResponseFormat responseFormat, User modifier, Resource resource, AuditingActionEnum actionEnum, ResourceVersionInfo prevResFields) {
350         auditResource(responseFormat, modifier, resource, resource.getName(), actionEnum, prevResFields, null, null);
351     }
352
353     public void auditResource(ResponseFormat responseFormat, User modifier, String resourceName, AuditingActionEnum actionEnum) {
354         auditResource(responseFormat, modifier, null, resourceName, actionEnum);
355     }
356
357     public void auditResource(ResponseFormat responseFormat, User modifier, Resource resource, AuditingActionEnum actionEnum) {
358         auditResource(responseFormat, modifier, resource, resource.getName(), actionEnum);
359     }
360
361     public void auditResource(ResponseFormat responseFormat, User modifier, Resource resource, String resourceName, AuditingActionEnum actionEnum) {
362         auditResource(responseFormat, modifier, resource, resourceName, actionEnum, ResourceVersionInfo.newBuilder().build(), null, null);
363     }
364
365     public void auditResource(ResponseFormat responseFormat, User modifier, Resource resource, String resourceName, AuditingActionEnum actionEnum,
366                               ResourceVersionInfo prevResFields, String currentArtifactUuid, ArtifactDefinition artifactDefinition) {
367         if (actionEnum != null) {
368             int status = responseFormat.getStatus();
369
370             String uuid = null;
371             String resourceCurrVersion = null;
372             String resourceCurrState = null;
373             String invariantUUID = null;
374             String resourceType = ComponentTypeEnum.RESOURCE.getValue();
375             String toscaNodeType = null;
376
377             log.trace(INSIDE_AUDITING_FOR_AUDIT_ACTION, actionEnum);
378
379             String message = getMessageString(responseFormat);
380
381             String artifactData = buildAuditingArtifactData(artifactDefinition);
382
383             if (resource != null) {
384                 resourceName = resource.getName();
385                 resourceCurrVersion = resource.getVersion();
386                 if (resource.getLifecycleState() != null) {
387                     resourceCurrState = resource.getLifecycleState().name();
388                 }
389                 if (resource.getResourceType() != null) {
390                     resourceType = resource.getResourceType().name();
391                 }
392                 invariantUUID =  resource.getInvariantUUID();
393                 uuid =  resource.getUUID();
394                 toscaNodeType = resource.getToscaResourceName();
395             }
396
397             AuditEventFactory factory = AuditResourceEventFactoryManager.createResourceEventFactory(
398                     actionEnum,
399                     CommonAuditData.newBuilder()
400                             .status(status)
401                             .description(message)
402                             .requestId(ThreadLocalsHolder.getUuid())
403                             .serviceInstanceId(uuid)
404                             .build(),
405                     new ResourceCommonInfo(resourceName, resourceType),
406                     prevResFields,
407                     ResourceVersionInfo.newBuilder()
408                             .artifactUuid(currentArtifactUuid)
409                             .state(resourceCurrState)
410                             .version(resourceCurrVersion)
411                             .build(),
412                     invariantUUID,
413                     modifier,
414                     artifactData, null, null, toscaNodeType);
415
416             getAuditingManager().auditEvent(factory);
417         }
418     }
419
420     private String getMessageString(ResponseFormat responseFormat) {
421         String message = "";
422         if (responseFormat.getMessageId() != null) {
423             message = responseFormat.getMessageId() + ": ";
424         }
425         message += responseFormat.getFormattedMessage();
426         return message;
427     }
428
429     public void auditDistributionDownload(ResponseFormat responseFormat, DistributionData distributionData) {
430         log.trace("Inside auditing");
431         int status = responseFormat.getStatus();
432
433         String message = getMessageString(responseFormat);
434
435         AuditDistributionDownloadEventFactory factory = new AuditDistributionDownloadEventFactory(
436                 CommonAuditData.newBuilder()
437                         .status(status)
438                         .description(message)
439                         .requestId(ThreadLocalsHolder.getUuid())
440                         .build(),
441                         distributionData);
442                 getAuditingManager().auditEvent(factory);
443     }
444
445     public void auditExternalGetAsset(ResponseFormat responseFormat, AuditingActionEnum actionEnum, DistributionData distributionData,
446                                       ResourceCommonInfo resourceCommonInfo, String requestId, String serviceInstanceId) {
447         log.trace(INSIDE_AUDITING_FOR_AUDIT_ACTION, actionEnum);
448
449         AuditEventFactory factory = new AuditAssetExternalApiEventFactory(actionEnum,
450                 CommonAuditData.newBuilder()
451                         .status(responseFormat.getStatus())
452                         .description(getMessageString(responseFormat))
453                         .requestId(requestId)
454                         .serviceInstanceId(serviceInstanceId)
455                         .build(),
456                 resourceCommonInfo, distributionData);
457
458         getAuditingManager().auditEvent(factory);
459     }
460
461     public void auditExternalGetAssetList(ResponseFormat responseFormat, AuditingActionEnum actionEnum, DistributionData distributionData, String requestId) {
462         log.trace(INSIDE_AUDITING_FOR_AUDIT_ACTION, actionEnum);
463
464         AuditEventFactory factory = new AuditAssetListExternalApiEventFactory(actionEnum,
465                 CommonAuditData.newBuilder()
466                         .status(responseFormat.getStatus())
467                         .description(getMessageString(responseFormat))
468                         .requestId(requestId)
469                          .build(),
470                 distributionData);
471
472         getAuditingManager().auditEvent(factory);
473     }
474
475     public void auditChangeLifecycleAction(ResponseFormat responseFormat, ComponentTypeEnum componentType, String requestId,
476                                            Component component, Component responseObject, DistributionData distributionData, User modifier) {
477
478         String invariantUuid = "";
479         String serviceInstanceId = "";
480         ResourceVersionInfo currResourceVersionInfo = null;
481         ResourceVersionInfo prevResourceVersionInfo = null;
482         ResourceCommonInfo resourceCommonInfo = new ResourceCommonInfo(componentType.getValue());
483
484         if (component != null) {
485             prevResourceVersionInfo = buildResourceVersionInfoFromComponent(component);
486             resourceCommonInfo.setResourceName(component.getName());
487         }
488
489         if (responseObject != null){
490             currResourceVersionInfo = buildResourceVersionInfoFromComponent(responseObject);
491             invariantUuid = responseObject.getInvariantUUID();
492             serviceInstanceId = responseObject.getUUID();
493         }
494         else if (component != null){
495             currResourceVersionInfo = buildResourceVersionInfoFromComponent(component);
496             invariantUuid = component.getInvariantUUID();
497             serviceInstanceId = component.getUUID();
498         }
499
500         if (prevResourceVersionInfo == null) {
501             prevResourceVersionInfo = ResourceVersionInfo.newBuilder()
502                     .build();
503         }
504         if (currResourceVersionInfo == null) {
505             currResourceVersionInfo = ResourceVersionInfo.newBuilder()
506                     .build();
507         }
508         AuditEventFactory factory = new AuditChangeLifecycleExternalApiEventFactory(
509                 CommonAuditData.newBuilder()
510                     .serviceInstanceId(serviceInstanceId)
511                     .requestId(requestId)
512                     .description(getMessageString(responseFormat))
513                     .status(responseFormat.getStatus())
514                     .build(),
515                 resourceCommonInfo, distributionData,
516                 prevResourceVersionInfo, currResourceVersionInfo,
517                 invariantUuid, modifier);
518
519         getAuditingManager().auditEvent(factory);
520     }
521
522     private ResourceVersionInfo buildResourceVersionInfoFromComponent(Component component) {
523         return ResourceVersionInfo.newBuilder()
524                 .version(component.getVersion())
525                 .state(component.getLifecycleState().name())
526                 .build();
527     }
528
529     public void auditExternalCrudApi(ResponseFormat responseFormat, AuditingActionEnum actionEnum, ResourceCommonInfo resourceCommonInfo, HttpServletRequest request,
530                                      ArtifactDefinition artifactDefinition, String artifactUuid) {
531         log.trace(INSIDE_AUDITING_FOR_AUDIT_ACTION, actionEnum);
532
533         ResourceVersionInfo currResourceVersionInfo;
534         User modifier = new User();
535         modifier.setUserId(request.getHeader(Constants.USER_ID_HEADER));
536         String artifactData = "";
537         DistributionData distributionData = new DistributionData(request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER), request.getRequestURI());
538         String requestId = request.getHeader(Constants.X_ECOMP_REQUEST_ID_HEADER);
539
540
541         if (artifactDefinition == null) {
542             currResourceVersionInfo = ResourceVersionInfo.newBuilder()
543                     .artifactUuid(artifactUuid)
544                     .build();
545         }
546         else {
547             currResourceVersionInfo = ResourceVersionInfo.newBuilder()
548                     .artifactUuid(artifactDefinition.getArtifactUUID())
549                     .version(artifactDefinition.getArtifactVersion())
550                     .build();
551             artifactData = buildAuditingArtifactData(artifactDefinition);
552             modifier.setUserId(artifactDefinition.getUserIdLastUpdater());
553         }
554         AuditEventFactory factory = new AuditCrudExternalApiArtifactEventFactory(actionEnum,
555                 CommonAuditData.newBuilder()
556                     .status(responseFormat.getStatus())
557                     .description(getMessageString(responseFormat))
558                     .requestId(requestId)
559                     .build(),
560                 resourceCommonInfo, distributionData, ResourceVersionInfo.newBuilder().build(), currResourceVersionInfo,
561                 null, modifier, artifactData);
562
563         getAuditingManager().auditEvent(factory);
564     }
565
566     public boolean isExternalApiEvent(AuditingActionEnum auditingActionEnum){
567         return auditingActionEnum != null && auditingActionEnum.getAuditingEsType().equals(AuditingTypesConstants.EXTERNAL_API_EVENT_TYPE);
568     }
569
570     public void auditCreateResourceExternalApi(ResponseFormat responseFormat, ResourceCommonInfo resourceCommonInfo, HttpServletRequest request,
571                                                Resource resource) {
572
573         String invariantUuid = null;
574         String serviceInstanceId = null;
575
576         User modifier = new User();
577         modifier.setUserId(request.getHeader(Constants.USER_ID_HEADER));
578         DistributionData distributionData = new DistributionData(request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER), request.getRequestURI());
579         String requestId = request.getHeader(Constants.X_ECOMP_REQUEST_ID_HEADER);
580
581         ResourceVersionInfo currResourceVersionInfo;
582
583         if( resource != null ){
584             currResourceVersionInfo = ResourceVersionInfo.newBuilder()
585                     .state(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())
586                     .version(ImportUtils.Constants.FIRST_NON_CERTIFIED_VERSION)
587                     .build();
588             resourceCommonInfo.setResourceName(resource.getName());
589             invariantUuid = resource.getInvariantUUID();
590             serviceInstanceId = resource.getUUID();
591         }
592         else {
593             currResourceVersionInfo = ResourceVersionInfo.newBuilder()
594                     .build();
595         }
596
597         AuditEventFactory factory = new AuditCreateResourceExternalApiEventFactory(
598                 CommonAuditData.newBuilder()
599                         .status(responseFormat.getStatus())
600                         .description(getMessageString(responseFormat))
601                         .requestId(requestId)
602                         .serviceInstanceId(serviceInstanceId)
603                         .build(),
604                 resourceCommonInfo, distributionData,
605                 currResourceVersionInfo, invariantUuid, modifier);
606
607         getAuditingManager().auditEvent(factory);
608     }
609
610     public void auditExternalActivateService(ResponseFormat responseFormat, DistributionData distributionData, String requestId, String serviceInstanceUuid, User modifier) {
611         AuditEventFactory factory = new AuditActivateServiceExternalApiEventFactory(
612                 CommonAuditData.newBuilder()
613                     .serviceInstanceId(serviceInstanceUuid)
614                     .description(getMessageString(responseFormat))
615                     .status(responseFormat.getStatus())
616                     .requestId(requestId)
617                     .build(),
618                 new ResourceCommonInfo(ComponentTypeEnum.SERVICE.name()), distributionData, "", modifier);
619         getAuditingManager().auditEvent(factory);
620     }
621
622     public void auditExternalDownloadArtifact(ResponseFormat responseFormat, ResourceCommonInfo resourceCommonInfo,
623                                               DistributionData distributionData, String requestId, String currArtifactUuid, String userId) {
624         User modifier = new User();
625         modifier.setUserId(userId);
626
627         AuditEventFactory factory = new AuditDownloadArtifactExternalApiEventFactory(
628                 CommonAuditData.newBuilder()
629                         .description(getMessageString(responseFormat))
630                         .status(responseFormat.getStatus())
631                         .requestId(requestId)
632                         .build(),
633                 resourceCommonInfo, distributionData,
634                 ResourceVersionInfo.newBuilder()
635                         .artifactUuid(currArtifactUuid)
636                         .build(),
637                 modifier);
638         getAuditingManager().auditEvent(factory);
639     }
640
641     private String buildAuditingArtifactData(ArtifactDefinition artifactDefinition) {
642         StringBuilder sb = new StringBuilder();
643         if (artifactDefinition != null) {
644             sb.append(artifactDefinition.getArtifactGroupType().getType())
645                     .append(",")
646                     .append("'")
647                     .append(artifactDefinition.getArtifactLabel())
648                     .append("'")
649                     .append(",")
650                     .append(artifactDefinition.getArtifactType())
651                     .append(",")
652                     .append(artifactDefinition.getArtifactName())
653                     .append(",")
654                     .append(artifactDefinition.getTimeout())
655                     .append(",")
656                     .append(artifactDefinition.getEsId());
657
658             sb.append(",");
659             sb.append(artifactDefinition.getArtifactVersion() != null ? artifactDefinition.getArtifactVersion() : " ");
660             sb.append(",");
661             sb.append(artifactDefinition.getArtifactUUID() != null ? artifactDefinition.getArtifactUUID() : " ");
662         }
663         return sb.toString();
664     }
665
666     public void auditCategory(ResponseFormat responseFormat, User modifier, String categoryName, String subCategoryName, String groupingName, AuditingActionEnum actionEnum, String componentType) {
667         log.trace(INSIDE_AUDITING_FOR_AUDIT_ACTION, actionEnum);
668
669         AuditEventFactory factory = new AuditCategoryEventFactory(actionEnum,
670                 CommonAuditData.newBuilder()
671                         .description(getMessageString(responseFormat))
672                         .status(responseFormat.getStatus())
673                         .requestId(ThreadLocalsHolder.getUuid())
674                         .build(),
675                 modifier, categoryName, subCategoryName, groupingName, componentType);
676
677         getAuditingManager().auditEvent(factory);
678     }
679
680     public ActionStatus convertFromStorageResponse(StorageOperationStatus storageResponse) {
681
682         return convertFromStorageResponse(storageResponse, ComponentTypeEnum.RESOURCE);
683     }
684
685     public ActionStatus convertFromStorageResponse(StorageOperationStatus storageResponse, ComponentTypeEnum type) {
686
687         ActionStatus responseEnum = ActionStatus.GENERAL_ERROR;
688         if (storageResponse == null) {
689             return responseEnum;
690         }
691         switch (storageResponse) {
692         case OK:
693             responseEnum = ActionStatus.OK;
694             break;
695         case CONNECTION_FAILURE:
696         case GRAPH_IS_LOCK:
697             responseEnum = ActionStatus.GENERAL_ERROR;
698             break;
699         case BAD_REQUEST:
700             responseEnum = ActionStatus.INVALID_CONTENT;
701             break;
702         case ENTITY_ALREADY_EXISTS:
703             responseEnum = ActionStatus.COMPONENT_NAME_ALREADY_EXIST;
704             break;
705         case PARENT_RESOURCE_NOT_FOUND:
706             responseEnum = ActionStatus.PARENT_RESOURCE_NOT_FOUND;
707             break;
708         case MULTIPLE_PARENT_RESOURCE_FOUND:
709             responseEnum = ActionStatus.MULTIPLE_PARENT_RESOURCE_FOUND;
710             break;
711         case NOT_FOUND:
712             if (ComponentTypeEnum.RESOURCE == type) {
713                 responseEnum = ActionStatus.RESOURCE_NOT_FOUND;
714             } else if (ComponentTypeEnum.PRODUCT == type) {
715                 responseEnum = ActionStatus.PRODUCT_NOT_FOUND;
716             } else {
717                 responseEnum = ActionStatus.SERVICE_NOT_FOUND;
718             }
719             break;
720         case FAILED_TO_LOCK_ELEMENT:
721             responseEnum = ActionStatus.COMPONENT_IN_USE;
722             break;
723         case ARTIFACT_NOT_FOUND:
724             responseEnum = ActionStatus.ARTIFACT_NOT_FOUND;
725             break;
726         case DISTR_ENVIRONMENT_NOT_AVAILABLE:
727             responseEnum = ActionStatus.DISTRIBUTION_ENVIRONMENT_NOT_AVAILABLE;
728             break;
729         case DISTR_ENVIRONMENT_NOT_FOUND:
730             responseEnum = ActionStatus.DISTRIBUTION_ENVIRONMENT_NOT_FOUND;
731             break;
732         case DISTR_ENVIRONMENT_SENT_IS_INVALID:
733             responseEnum = ActionStatus.DISTRIBUTION_ENVIRONMENT_INVALID;
734             break;
735         case INVALID_TYPE:
736             responseEnum = ActionStatus.INVALID_CONTENT;
737             break;
738         case INVALID_VALUE:
739             responseEnum = ActionStatus.INVALID_CONTENT;
740             break;
741         case CSAR_NOT_FOUND:
742             responseEnum = ActionStatus.CSAR_NOT_FOUND;
743             break;
744         case PROPERTY_NAME_ALREADY_EXISTS:
745             responseEnum = ActionStatus.PROPERTY_NAME_ALREADY_EXISTS;
746             break;
747         case MATCH_NOT_FOUND:
748             responseEnum = ActionStatus.COMPONENT_SUB_CATEGORY_NOT_FOUND_FOR_CATEGORY;
749             break;
750         case CATEGORY_NOT_FOUND:
751             responseEnum = ActionStatus.COMPONENT_CATEGORY_NOT_FOUND;
752             break;
753         case INVALID_PROPERTY:
754             responseEnum = ActionStatus.INVALID_PROPERTY;
755             break;
756         case COMPONENT_IS_ARCHIVED:
757             responseEnum = ActionStatus.COMPONENT_IS_ARCHIVED;
758             break;
759         case DECLARED_INPUT_USED_BY_OPERATION:
760             responseEnum = ActionStatus.DECLARED_INPUT_USED_BY_OPERATION;
761             break;
762        default:
763             responseEnum = ActionStatus.GENERAL_ERROR;
764             break;
765         }
766         log.debug(CONVERT_STORAGE_RESPONSE_TO_ACTION_RESPONSE, storageResponse, responseEnum);
767         return responseEnum;
768     }
769
770     public ActionStatus convertFromToscaError(ToscaError toscaError) {
771         ActionStatus responseEnum = ActionStatus.GENERAL_ERROR;
772         if (toscaError == null) {
773             return responseEnum;
774         }
775         switch (toscaError) {// TODO match errors
776             case NODE_TYPE_CAPABILITY_ERROR:
777             case NOT_SUPPORTED_TOSCA_TYPE:
778             case NODE_TYPE_REQUIREMENT_ERROR:
779                 responseEnum = ActionStatus.INVALID_CONTENT;
780                 break;
781             default:
782                 responseEnum = ActionStatus.GENERAL_ERROR;
783                 break;
784         }
785         return responseEnum;
786     }
787
788     public ActionStatus convertFromStorageResponseForCapabilityType(StorageOperationStatus storageResponse) {
789         ActionStatus responseEnum = ActionStatus.GENERAL_ERROR;
790
791         switch (storageResponse) {
792         case OK:
793             responseEnum = ActionStatus.OK;
794             break;
795         case CONNECTION_FAILURE:
796         case GRAPH_IS_LOCK:
797             responseEnum = ActionStatus.GENERAL_ERROR;
798             break;
799         case BAD_REQUEST:
800             responseEnum = ActionStatus.INVALID_CONTENT;
801             break;
802         case ENTITY_ALREADY_EXISTS:
803             responseEnum = ActionStatus.CAPABILITY_TYPE_ALREADY_EXIST;
804             break;
805         case SCHEMA_VIOLATION:
806             responseEnum = ActionStatus.CAPABILITY_TYPE_ALREADY_EXIST;
807             break;
808         default:
809             responseEnum = ActionStatus.GENERAL_ERROR;
810             break;
811         }
812         log.debug(CONVERT_STORAGE_RESPONSE_TO_ACTION_RESPONSE, storageResponse, responseEnum);
813         return responseEnum;
814     }
815
816     public ActionStatus convertFromStorageResponseForLifecycleType(StorageOperationStatus storageResponse) {
817         ActionStatus responseEnum = ActionStatus.GENERAL_ERROR;
818
819         switch (storageResponse) {
820         case OK:
821             responseEnum = ActionStatus.OK;
822             break;
823         case CONNECTION_FAILURE:
824         case GRAPH_IS_LOCK:
825             responseEnum = ActionStatus.GENERAL_ERROR;
826             break;
827         case BAD_REQUEST:
828             responseEnum = ActionStatus.INVALID_CONTENT;
829             break;
830         case ENTITY_ALREADY_EXISTS:
831             responseEnum = ActionStatus.LIFECYCLE_TYPE_ALREADY_EXIST;
832             break;
833         case SCHEMA_VIOLATION:
834             responseEnum = ActionStatus.LIFECYCLE_TYPE_ALREADY_EXIST;
835             break;
836         default:
837             responseEnum = ActionStatus.GENERAL_ERROR;
838             break;
839         }
840         log.debug(CONVERT_STORAGE_RESPONSE_TO_ACTION_RESPONSE, storageResponse, responseEnum);
841         return responseEnum;
842     }
843
844     public ActionStatus convertFromStorageResponseForResourceInstance(StorageOperationStatus storageResponse, boolean isRelation) {
845         ActionStatus responseEnum = ActionStatus.GENERAL_ERROR;
846
847         switch (storageResponse) {
848         case OK:
849             responseEnum = ActionStatus.OK;
850             break;
851         case INVALID_ID:
852             responseEnum = ActionStatus.RESOURCE_INSTANCE_BAD_REQUEST;
853             break;
854         case INVALID_PROPERTY:
855             responseEnum = ActionStatus.INVALID_PROPERTY;
856             break;
857         case GRAPH_IS_LOCK:
858             responseEnum = ActionStatus.GENERAL_ERROR;
859             break;
860         case BAD_REQUEST:
861             responseEnum = ActionStatus.INVALID_CONTENT;
862             break;
863         case MATCH_NOT_FOUND:
864             responseEnum = ActionStatus.RESOURCE_INSTANCE_MATCH_NOT_FOUND;
865             break;
866         case SCHEMA_VIOLATION:
867             responseEnum = ActionStatus.RESOURCE_INSTANCE_ALREADY_EXIST;
868             break;
869         case NOT_FOUND:
870             if (isRelation) {
871                 responseEnum = ActionStatus.RESOURCE_INSTANCE_RELATION_NOT_FOUND;
872             } else {
873                 responseEnum = ActionStatus.RESOURCE_INSTANCE_NOT_FOUND;
874             }
875             break;
876         default:
877             responseEnum = ActionStatus.GENERAL_ERROR;
878             break;
879         }
880         log.debug(CONVERT_STORAGE_RESPONSE_TO_ACTION_RESPONSE, storageResponse, responseEnum);
881         return responseEnum;
882     }
883
884     public ResponseFormat getResponseFormatForResourceInstance(ActionStatus actionStatus, String serviceName, String resourceInstanceName) {
885         ResponseFormat responseFormat;
886
887         if (actionStatus == ActionStatus.RESOURCE_INSTANCE_NOT_FOUND) {
888             responseFormat = getResponseFormat(actionStatus, resourceInstanceName);
889         }
890         else {
891             responseFormat = getResponseFormat(actionStatus, serviceName);
892         }
893         return responseFormat;
894     }
895
896     public ResponseFormat getResponseFormatForResourceInstanceProperty(ActionStatus actionStatus, String resourceInstanceName) {
897         ResponseFormat responseFormat;
898         if (actionStatus == ActionStatus.RESOURCE_INSTANCE_NOT_FOUND) {
899             responseFormat = getResponseFormat(actionStatus, resourceInstanceName);
900         }
901         else {
902             responseFormat = getResponseFormat(actionStatus);
903         }
904         return responseFormat;
905     }
906
907     public ActionStatus convertFromStorageResponseForResourceInstanceProperty(StorageOperationStatus storageResponse) {
908         ActionStatus responseEnum = ActionStatus.GENERAL_ERROR;
909
910         switch (storageResponse) {
911         case OK:
912             responseEnum = ActionStatus.OK;
913             break;
914         case INVALID_ID:
915             responseEnum = ActionStatus.RESOURCE_INSTANCE_BAD_REQUEST;
916             break;
917         case GRAPH_IS_LOCK:
918             responseEnum = ActionStatus.GENERAL_ERROR;
919             break;
920         case BAD_REQUEST:
921             responseEnum = ActionStatus.INVALID_CONTENT;
922             break;
923         case MATCH_NOT_FOUND:
924             responseEnum = ActionStatus.RESOURCE_INSTANCE_MATCH_NOT_FOUND;
925             break;
926         case SCHEMA_VIOLATION:
927             responseEnum = ActionStatus.RESOURCE_INSTANCE_ALREADY_EXIST;
928             break;
929         case NOT_FOUND:
930             responseEnum = ActionStatus.RESOURCE_INSTANCE_NOT_FOUND;
931             break;
932         default:
933             responseEnum = ActionStatus.GENERAL_ERROR;
934             break;
935         }
936         log.debug(CONVERT_STORAGE_RESPONSE_TO_ACTION_RESPONSE, storageResponse, responseEnum);
937         return responseEnum;
938     }
939
940     public void auditComponent(ResponseFormat responseFormat, User modifier, Component component, AuditingActionEnum actionEnum, ResourceCommonInfo resourceCommonInfo, ResourceVersionInfo prevComponent, String comment) {
941         auditComponent(responseFormat, modifier, component, actionEnum, resourceCommonInfo, prevComponent, null, comment, null, null);
942     }
943
944     public void auditComponentAdmin(ResponseFormat responseFormat, User modifier, Component component, AuditingActionEnum actionEnum, ComponentTypeEnum typeEnum) {
945         auditComponent(responseFormat, modifier, component, actionEnum, new ResourceCommonInfo(typeEnum.getValue()), ResourceVersionInfo.newBuilder().build());
946     }
947
948     public void auditComponentAdmin(ResponseFormat responseFormat, User modifier, Component component, AuditingActionEnum actionEnum, ComponentTypeEnum typeEnum, String comment) {
949         auditComponent(responseFormat, modifier, component, actionEnum, new ResourceCommonInfo(typeEnum.getValue()), ResourceVersionInfo.newBuilder().build(), null,
950                 comment, null, null);
951     }
952
953     public void auditComponentAdmin(ResponseFormat responseFormat, User modifier, Component component, AuditingActionEnum actionEnum, ComponentTypeEnum typeEnum, ResourceVersionInfo prevComponent) {
954         auditComponent(responseFormat, modifier, component, actionEnum, new ResourceCommonInfo(typeEnum.getValue()), prevComponent);
955     }
956
957     public void auditComponent(ResponseFormat responseFormat, User modifier, Component component, AuditingActionEnum actionEnum, ResourceCommonInfo resourceCommonInfo, ResourceVersionInfo prevComponent) {
958         auditComponent(responseFormat, modifier, component, actionEnum, resourceCommonInfo, prevComponent, null, null, null, null);
959     }
960
961     public void auditComponent(ResponseFormat responseFormat, User modifier, AuditingActionEnum actionEnum, ResourceCommonInfo resourceCommonInfo, String comment) {
962         auditComponent(responseFormat, modifier, null, actionEnum, resourceCommonInfo, ResourceVersionInfo.newBuilder().build(), null, comment, null, null);
963     }
964
965     public void auditComponent(ResponseFormat responseFormat, User modifier, Component component, AuditingActionEnum actionEnum, ResourceCommonInfo resourceCommonInfo, ResourceVersionInfo prevComponent, ResourceVersionInfo currComponent) {
966         auditComponent(responseFormat, modifier, component, actionEnum, resourceCommonInfo, prevComponent, currComponent, null, null, null);
967     }
968
969     public void auditComponent(ResponseFormat responseFormat, User modifier, Component component, AuditingActionEnum actionEnum, ResourceCommonInfo resourceCommonInfo, ResourceVersionInfo prevComponent, ResourceVersionInfo currComponent,
970                                String comment, ArtifactDefinition artifactDefinition, String did) {
971         if (actionEnum != null) {
972             String uuid = null;
973             String currState = null;
974             String invariantUUID = null;
975             String currArtifactUid = null;
976             String currVersion = null;
977             String dcurrStatus = null;
978
979             log.trace(INSIDE_AUDITING_FOR_AUDIT_ACTION, actionEnum);
980
981             String message = getMessageString(responseFormat);
982             int status = responseFormat.getStatus();
983             String artifactData = buildAuditingArtifactData(artifactDefinition);
984
985             if (component != null) {
986                 // fields that are filled during creation and might still be empty
987                 if (component.getLifecycleState() != null) {
988                     currState = component.getLifecycleState().name();
989                 }
990                 uuid = component.getUUID();
991                 invariantUUID = component.getInvariantUUID();
992                 currVersion = component.getVersion();
993                 if (StringUtils.isEmpty(resourceCommonInfo.getResourceName())) {
994                     resourceCommonInfo.setResourceName(component.getComponentMetadataDefinition().getMetadataDataDefinition().getName());
995                 }
996             }
997             if (currComponent != null) {
998                 currArtifactUid = currComponent.getArtifactUuid();
999                 dcurrStatus = currComponent.getDistributionStatus();
1000                 if (currState == null) { //probably it was not set
1001                     currState = currComponent.getState();
1002                 }
1003                 if (currVersion == null) { //probably it was not set
1004                     currVersion = currComponent.getVersion();
1005                 }
1006             }
1007             AuditEventFactory factory = AuditResourceEventFactoryManager.createResourceEventFactory(
1008                     actionEnum,
1009                     CommonAuditData.newBuilder()
1010                             .status(status)
1011                             .description(message)
1012                             .requestId(ThreadLocalsHolder.getUuid())
1013                             .serviceInstanceId(uuid)
1014                             .build(),
1015                     resourceCommonInfo, prevComponent,
1016                     ResourceVersionInfo.newBuilder()
1017                             .artifactUuid(currArtifactUid)
1018                             .state(currState)
1019                             .version(currVersion)
1020                             .distributionStatus(dcurrStatus)
1021                             .build(),
1022                     invariantUUID,
1023                     modifier, artifactData, comment, did, null);
1024
1025             getAuditingManager().auditEvent(factory);
1026         }
1027     }
1028
1029     public void auditDistributionEngine(AuditingActionEnum action, String environmentName, DistributionTopicData distributionTopicData, String status) {
1030         auditDistributionEngine(action, environmentName, distributionTopicData, null, null, status);
1031     }
1032
1033
1034      public void auditDistributionEngine(AuditingActionEnum action, String environmentName, DistributionTopicData distributionTopicData, String role, String apiKey, String status) {
1035         AuditEventFactory factory = AuditDistributionEngineEventFactoryManager.createDistributionEngineEventFactory(action,
1036                 environmentName, distributionTopicData, role, apiKey, status);
1037         getAuditingManager().auditEvent(factory);
1038     }
1039
1040
1041     public void auditEnvironmentEngine(AuditingActionEnum actionEnum, String environmentID,
1042                                        String environmentType, String action, String environmentName, String tenantContext) {
1043         AuditEventFactory factory = new AuditEcompOpEnvEventFactory(actionEnum, environmentID, environmentName,
1044                 environmentType, action, tenantContext);
1045         getAuditingManager().auditEvent(factory);
1046     }
1047
1048     public void auditDistributionNotification(String serviceUUID, String resourceName, String resourceType, String currVersion, User modifier, String environmentName, String currState,
1049                                               String topicName, String distributionId, String description, String status, String workloadContext, String tenant) {
1050
1051         AuditEventFactory factory = new AuditDistributionNotificationEventFactory(
1052                 CommonAuditData.newBuilder()
1053                     .serviceInstanceId(serviceUUID)
1054                     .status(status)
1055                     .description(description)
1056                     .requestId(ThreadLocalsHolder.getUuid())
1057                     .build(),
1058                 new ResourceCommonInfo(resourceName, resourceType),
1059                 ResourceVersionInfo.newBuilder()
1060                     .state(currState)
1061                     .version(currVersion)
1062                     .build(),
1063                 distributionId, modifier, topicName,
1064                 new OperationalEnvAuditData(environmentName, workloadContext, tenant));
1065
1066         getAuditingManager().auditEvent(factory);
1067     }
1068
1069     public void auditAuthEvent(String url, String user, String authStatus, String realm) {
1070         AuditEventFactory factory = new AuditAuthRequestEventFactory(
1071                 CommonAuditData.newBuilder()
1072                 .requestId(ThreadLocalsHolder.getUuid())
1073                 .build(),
1074                 user, url, realm, authStatus);
1075         getAuditingManager().auditEvent(factory);
1076     }
1077
1078     public void auditDistributionStatusNotification(String distributionId, String consumerId, String topicName, String resourceUrl, String statusTime, String status, String errorReason) {
1079         ThreadLocalsHolder.setUuid(distributionId);
1080
1081         AuditEventFactory factory =  new AuditDistributionStatusEventFactory(
1082                 CommonAuditData.newBuilder()
1083                 .description(errorReason)
1084                 .status(status)
1085                 .requestId(distributionId)
1086                 .build(),
1087                 new DistributionData(consumerId, resourceUrl),
1088                 distributionId, topicName, statusTime);
1089
1090         getAuditingManager().auditEvent(factory);
1091     }
1092
1093     public void auditGetUebCluster(String consumerId, String status, String description) {
1094         AuditEventFactory factory = new AuditGetUebClusterEventFactory(
1095                 CommonAuditData.newBuilder()
1096                         .description(description)
1097                         .status(status)
1098                         .requestId(ThreadLocalsHolder.getUuid())
1099                         .build(),
1100                 consumerId);
1101
1102         getAuditingManager().auditEvent(factory);
1103     }
1104
1105     public void auditMissingInstanceIdAsDistributionEngineEvent(AuditingActionEnum actionEnum, String status) {
1106         AuditEventFactory factory = AuditDistributionEngineEventFactoryManager.createDistributionEngineEventFactory(
1107                 actionEnum, "",
1108                 DistributionTopicData.newBuilder()
1109                         .build(), null, null, status);
1110         getAuditingManager().auditEvent(factory);
1111     }
1112
1113
1114     public void auditRegisterOrUnRegisterEvent(AuditingActionEnum action, String consumerId, String apiPublicKey, String envName, String status, String distributionStatus, String notifTopicName, String statusTopicName) {
1115         String appliedStatus = !StringUtils.isEmpty(status) ? status : distributionStatus;
1116
1117         AuditEventFactory factory = new AuditRegUnregDistributionEngineEventFactory(action,
1118                 CommonAuditData.newBuilder()
1119                     .requestId(ThreadLocalsHolder.getUuid())
1120                     .status(appliedStatus)
1121                     .build(),
1122                 DistributionTopicData.newBuilder()
1123                     .statusTopic(statusTopicName)
1124                     .notificationTopic(notifTopicName)
1125                     .build(),
1126                 consumerId, apiPublicKey, envName);
1127
1128         getAuditingManager().auditEvent(factory);
1129     }
1130
1131     public void auditServiceDistributionDeployed(String serviceName, String serviceVersion, String serviceUUID, String distributionId, String status, String desc, User modifier) {
1132
1133         AuditEventFactory factory = new AuditDistributionDeployEventFactory(
1134                 CommonAuditData.newBuilder()
1135                     .requestId(ThreadLocalsHolder.getUuid())
1136                     .serviceInstanceId(serviceUUID)
1137                     .status(status)
1138                     .description(desc)
1139                     .build(),
1140                 new ResourceCommonInfo(serviceName, "Service"),
1141                 distributionId,
1142                 modifier,
1143                 serviceVersion);
1144
1145         getAuditingManager().auditEvent(factory);
1146
1147     }
1148
1149     public void auditConsumerCredentialsEvent(AuditingActionEnum actionEnum, ConsumerDefinition consumer, ResponseFormat responseFormat, User modifier) {
1150         AuditEventFactory factory = new AuditConsumerEventFactory(actionEnum,
1151                 CommonAuditData.newBuilder()
1152                 .description(getMessageString(responseFormat))
1153                 .status(responseFormat.getStatus())
1154                 .requestId(ThreadLocalsHolder.getUuid())
1155                 .build(),
1156                 modifier, consumer);
1157
1158         getAuditingManager().auditEvent(factory);
1159     }
1160
1161     public void auditGetUsersList(User user, String details, ResponseFormat responseFormat) {
1162
1163         AuditEventFactory factory = new AuditGetUsersListEventFactory(
1164                 CommonAuditData.newBuilder()
1165                         .description(getMessageString(responseFormat))
1166                         .status(responseFormat.getStatus())
1167                         .requestId(ThreadLocalsHolder.getUuid())
1168                         .build(),
1169                 user, details);
1170         getAuditingManager().auditEvent(factory);
1171     }
1172
1173     public void auditAdminUserAction(AuditingActionEnum actionEnum, User modifier, User userBefore, User userAfter, ResponseFormat responseFormat) {
1174
1175         AuditEventFactory factory = new AuditUserAdminEventFactory(actionEnum,
1176                 CommonAuditData.newBuilder()
1177                         .description(getMessageString(responseFormat))
1178                         .status(responseFormat.getStatus())
1179                         .requestId(ThreadLocalsHolder.getUuid())
1180                         .build(),
1181                 modifier, userBefore, userAfter);
1182
1183         getAuditingManager().auditEvent(factory);
1184     }
1185
1186     public void auditUserAccess(User user, ResponseFormat responseFormat) {
1187
1188         AuditEventFactory factory = new AuditUserAccessEventFactory(CommonAuditData.newBuilder()
1189                 .description(getMessageString(responseFormat))
1190                 .status(responseFormat.getStatus())
1191                 .requestId(ThreadLocalsHolder.getUuid())
1192                 .build(),
1193                 user);
1194
1195         getAuditingManager().auditEvent(factory);
1196     }
1197
1198     public void auditGetCategoryHierarchy(User user, String details, ResponseFormat responseFormat) {
1199
1200         AuditEventFactory factory = new AuditGetCategoryHierarchyEventFactory(CommonAuditData.newBuilder()
1201                         .description(getMessageString(responseFormat))
1202                         .status(responseFormat.getStatus())
1203                         .requestId(ThreadLocalsHolder.getUuid())
1204                         .build(),
1205                 user, details);
1206
1207         getAuditingManager().auditEvent(factory);
1208     }
1209
1210     public ResponseFormat getResponseFormatByComponent(ActionStatus actionStatus, Component component, ComponentTypeEnum type) {
1211         if (component == null) {
1212             return getResponseFormat(actionStatus);
1213         }
1214         ResponseFormat responseFormat;
1215
1216         switch (actionStatus) {
1217             case COMPONENT_VERSION_ALREADY_EXIST:
1218                 responseFormat = getResponseFormat(ActionStatus.COMPONENT_VERSION_ALREADY_EXIST, type.getValue(), component.getVersion());
1219                 break;
1220             case RESOURCE_NOT_FOUND:
1221                 responseFormat = getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, component.getComponentMetadataDefinition().getMetadataDataDefinition().getName());
1222                 break;
1223             case COMPONENT_NAME_ALREADY_EXIST:
1224                 responseFormat = getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, type.getValue(), component.getComponentMetadataDefinition().getMetadataDataDefinition().getName());
1225                 break;
1226             case COMPONENT_IN_USE:
1227                 responseFormat = getResponseFormat(ActionStatus.COMPONENT_IN_USE, type.name().toLowerCase(), component.getUniqueId());
1228                 break;
1229             case SERVICE_DEPLOYMENT_ARTIFACT_NOT_FOUND:
1230                 responseFormat = getResponseFormat(ActionStatus.SERVICE_DEPLOYMENT_ARTIFACT_NOT_FOUND, component.getComponentMetadataDefinition().getMetadataDataDefinition().getName());
1231                 break;
1232             default:
1233                 responseFormat = getResponseFormat(actionStatus);
1234                 break;
1235         }
1236         return responseFormat;
1237     }
1238
1239     public boolean validateStringNotEmpty(String value) {
1240         return value != null && !value.trim().isEmpty();
1241     }
1242
1243     public ActionStatus convertFromStorageResponseForAdditionalInformation(StorageOperationStatus storageResponse) {
1244         ActionStatus responseEnum;
1245
1246         switch (storageResponse) {
1247         case OK:
1248             responseEnum = ActionStatus.OK;
1249             break;
1250         case ENTITY_ALREADY_EXISTS:
1251             responseEnum = ActionStatus.COMPONENT_NAME_ALREADY_EXIST;
1252             break;
1253         case INVALID_ID:
1254             responseEnum = ActionStatus.ADDITIONAL_INFORMATION_NOT_FOUND;
1255             break;
1256         default:
1257             responseEnum = ActionStatus.GENERAL_ERROR;
1258             break;
1259         }
1260         log.debug(CONVERT_STORAGE_RESPONSE_TO_ACTION_RESPONSE, storageResponse, responseEnum);
1261         return responseEnum;
1262     }
1263
1264     public ActionStatus convertFromResultStatusEnum(ResultStatusEnum resultStatus, JsonPresentationFields elementType) {
1265         ActionStatus responseEnum = ActionStatus.GENERAL_ERROR;
1266         switch (resultStatus) {
1267         case OK:
1268             responseEnum = ActionStatus.OK;
1269             break;
1270         case ELEMENT_NOT_FOUND:
1271             if(elementType!= null && elementType == JsonPresentationFields.PROPERTY){
1272                 responseEnum = ActionStatus.PROPERTY_NOT_FOUND;
1273             }
1274         break;
1275         case INVALID_PROPERTY_DEFAULT_VALUE:
1276         case INVALID_PROPERTY_TYPE:
1277         case INVALID_PROPERTY_VALUE:
1278         case INVALID_PROPERTY_NAME:
1279         case MISSING_ENTRY_SCHEMA_TYPE:
1280             responseEnum = ActionStatus.INVALID_PROPERTY;
1281             break;
1282         default:
1283             responseEnum = ActionStatus.GENERAL_ERROR;
1284             break;
1285         }
1286         return responseEnum;
1287     }
1288
1289     public ResponseFormat getResponseFormatAdditionalProperty(ActionStatus actionStatus, AdditionalInfoParameterInfo additionalInfoParameterInfo, NodeTypeEnum nodeType, AdditionalInformationEnum labelOrValue) {
1290
1291         if (additionalInfoParameterInfo == null) {
1292             additionalInfoParameterInfo = new AdditionalInfoParameterInfo();
1293         }
1294         if (labelOrValue == null) {
1295             labelOrValue = AdditionalInformationEnum.None;
1296         }
1297
1298         ResponseFormat responseFormat = null;
1299         switch (actionStatus) {
1300             case COMPONENT_NAME_ALREADY_EXIST:
1301                 responseFormat = getResponseFormat(actionStatus, "Additional parameter", additionalInfoParameterInfo.getKey());
1302                 break;
1303             case ADDITIONAL_INFORMATION_EXCEEDS_LIMIT:
1304                 responseFormat = getResponseFormat(actionStatus, labelOrValue.name().toLowerCase(), ValidationUtils.ADDITIONAL_INFORMATION_KEY_MAX_LENGTH.toString());
1305                 break;
1306             case ADDITIONAL_INFORMATION_MAX_NUMBER_REACHED:
1307                 responseFormat = getResponseFormat(actionStatus, nodeType.name().toLowerCase());
1308                 break;
1309             case ADDITIONAL_INFORMATION_EMPTY_STRING_NOT_ALLOWED:
1310                 responseFormat = getResponseFormat(actionStatus);
1311                 break;
1312             case ADDITIONAL_INFORMATION_KEY_NOT_ALLOWED_CHARACTERS:
1313                 responseFormat = getResponseFormat(actionStatus);
1314                 break;
1315             case ADDITIONAL_INFORMATION_VALUE_NOT_ALLOWED_CHARACTERS:
1316                 responseFormat = getResponseFormat(actionStatus);
1317                 break;
1318             case ADDITIONAL_INFORMATION_NOT_FOUND:
1319                 responseFormat = getResponseFormat(actionStatus);
1320                 break;
1321             default:
1322                 responseFormat = getResponseFormat(actionStatus);
1323                 break;
1324         }
1325
1326         return responseFormat;
1327     }
1328
1329     public ResponseFormat getResponseFormatAdditionalProperty(ActionStatus actionStatus) {
1330         return getResponseFormatAdditionalProperty(actionStatus, null, null, null);
1331     }
1332
1333     public ActionStatus convertFromStorageResponseForConsumer(StorageOperationStatus storageResponse) {
1334         ActionStatus responseEnum = ActionStatus.GENERAL_ERROR;
1335
1336         switch (storageResponse) {
1337         case OK:
1338             responseEnum = ActionStatus.OK;
1339             break;
1340         case CONNECTION_FAILURE:
1341         case GRAPH_IS_LOCK:
1342             responseEnum = ActionStatus.GENERAL_ERROR;
1343             break;
1344         case BAD_REQUEST:
1345             responseEnum = ActionStatus.INVALID_CONTENT;
1346             break;
1347         case ENTITY_ALREADY_EXISTS:
1348             responseEnum = ActionStatus.CONSUMER_ALREADY_EXISTS;
1349             break;
1350         case SCHEMA_VIOLATION:
1351             responseEnum = ActionStatus.CONSUMER_ALREADY_EXISTS;
1352             break;
1353         case NOT_FOUND:
1354             responseEnum = ActionStatus.ECOMP_USER_NOT_FOUND;
1355             break;
1356         default:
1357             responseEnum = ActionStatus.GENERAL_ERROR;
1358             break;
1359         }
1360         log.debug(CONVERT_STORAGE_RESPONSE_TO_ACTION_RESPONSE, storageResponse, responseEnum);
1361         return responseEnum;
1362     }
1363
1364     public ActionStatus convertFromStorageResponseForGroupType(StorageOperationStatus storageResponse) {
1365         ActionStatus responseEnum = ActionStatus.GENERAL_ERROR;
1366
1367         switch (storageResponse) {
1368         case OK:
1369             responseEnum = ActionStatus.OK;
1370             break;
1371         case CONNECTION_FAILURE:
1372         case GRAPH_IS_LOCK:
1373             responseEnum = ActionStatus.GENERAL_ERROR;
1374             break;
1375         case BAD_REQUEST:
1376             responseEnum = ActionStatus.INVALID_CONTENT;
1377             break;
1378         case ENTITY_ALREADY_EXISTS:
1379             responseEnum = ActionStatus.GROUP_TYPE_ALREADY_EXIST;
1380             break;
1381         case SCHEMA_VIOLATION:
1382             responseEnum = ActionStatus.GROUP_TYPE_ALREADY_EXIST;
1383             break;
1384         default:
1385             responseEnum = ActionStatus.GENERAL_ERROR;
1386             break;
1387         }
1388         log.debug(CONVERT_STORAGE_RESPONSE_TO_ACTION_RESPONSE, storageResponse, responseEnum);
1389         return responseEnum;
1390     }
1391
1392     public ActionStatus convertFromStorageResponseForDataType(StorageOperationStatus storageResponse) {
1393         ActionStatus responseEnum = ActionStatus.GENERAL_ERROR;
1394
1395         switch (storageResponse) {
1396         case OK:
1397             responseEnum = ActionStatus.OK;
1398             break;
1399         case CONNECTION_FAILURE:
1400         case GRAPH_IS_LOCK:
1401             responseEnum = ActionStatus.GENERAL_ERROR;
1402             break;
1403         case BAD_REQUEST:
1404             responseEnum = ActionStatus.INVALID_CONTENT;
1405             break;
1406         case ENTITY_ALREADY_EXISTS:
1407             responseEnum = ActionStatus.DATA_TYPE_ALREADY_EXIST;
1408             break;
1409         case SCHEMA_VIOLATION:
1410             responseEnum = ActionStatus.DATA_TYPE_ALREADY_EXIST;
1411             break;
1412         case CANNOT_UPDATE_EXISTING_ENTITY:
1413             responseEnum = ActionStatus.DATA_TYPE_CANNOT_BE_UPDATED_BAD_REQUEST;
1414             break;
1415         default:
1416             responseEnum = ActionStatus.GENERAL_ERROR;
1417             break;
1418         }
1419         log.debug(CONVERT_STORAGE_RESPONSE_TO_ACTION_RESPONSE, storageResponse, responseEnum);
1420         return responseEnum;
1421     }
1422
1423     public ResponseFormat getResponseFormatByGroupType(ActionStatus actionStatus, GroupTypeDefinition groupType) {
1424         if (groupType == null) {
1425             return getResponseFormat(actionStatus);
1426         }
1427         ResponseFormat responseFormat;
1428
1429         switch (actionStatus) {
1430             case GROUP_MEMBER_EMPTY:
1431             case GROUP_TYPE_ALREADY_EXIST:
1432                 responseFormat = getResponseFormat(actionStatus, groupType.getType());
1433                 break;
1434             default:
1435                 responseFormat = getResponseFormat(actionStatus);
1436                 break;
1437         }
1438         return responseFormat;
1439
1440     }
1441
1442     public ResponseFormat getResponseFormatByPolicyType(ActionStatus actionStatus, PolicyTypeDefinition policyType) {
1443         if (policyType == null) {
1444             return getResponseFormat(actionStatus);
1445         }
1446
1447         ResponseFormat responseFormat;
1448         if (actionStatus == ActionStatus.POLICY_TYPE_ALREADY_EXIST) {
1449             responseFormat = getResponseFormat(actionStatus, policyType.getType());
1450         }
1451         else {
1452             responseFormat = getResponseFormat(actionStatus);
1453         }
1454         return responseFormat;
1455
1456     }
1457
1458     public ResponseFormat getResponseFormatByDataType(ActionStatus actionStatus, DataTypeDefinition dataType, List<String> properties) {
1459         if (dataType == null) {
1460             return getResponseFormat(actionStatus);
1461         }
1462         ResponseFormat responseFormat;
1463
1464         switch (actionStatus) {
1465             case DATA_TYPE_ALREADY_EXIST:
1466                 responseFormat = getResponseFormat(actionStatus, dataType.getName());
1467                 break;
1468             case DATA_TYPE_NOR_PROPERTIES_NEITHER_DERIVED_FROM:
1469                 responseFormat = getResponseFormat(actionStatus, dataType.getName());
1470                 break;
1471             case DATA_TYPE_PROPERTIES_CANNOT_BE_EMPTY:
1472                 responseFormat = getResponseFormat(actionStatus, dataType.getName());
1473                 break;
1474             case DATA_TYPE_PROPERTY_ALREADY_DEFINED_IN_ANCESTOR:
1475                 responseFormat = getResponseFormat(actionStatus, dataType.getName(), properties == null ? "" : String.valueOf(properties));
1476                 break;
1477             case DATA_TYPE_DERIVED_IS_MISSING:
1478                 responseFormat = getResponseFormat(actionStatus, dataType.getDerivedFromName());
1479                 break;
1480             case DATA_TYPE_DUPLICATE_PROPERTY:
1481                 responseFormat = getResponseFormat(actionStatus, dataType.getName());
1482                 break;
1483             case DATA_TYPE_PROEPRTY_CANNOT_HAVE_SAME_TYPE_OF_DATA_TYPE:
1484                 responseFormat = getResponseFormat(actionStatus, dataType.getName(), properties == null ? "" : String.valueOf(properties));
1485                 break;
1486             case DATA_TYPE_CANNOT_HAVE_PROPERTIES:
1487                 responseFormat = getResponseFormat(actionStatus, dataType.getName());
1488                 break;
1489             case DATA_TYPE_CANNOT_BE_UPDATED_BAD_REQUEST:
1490                 responseFormat = getResponseFormat(actionStatus, dataType.getName());
1491                 break;
1492
1493             default:
1494                 responseFormat = getResponseFormat(actionStatus);
1495                 break;
1496         }
1497         return responseFormat;
1498     }
1499
1500     public StorageOperationStatus convertToStorageOperationStatus(CassandraOperationStatus cassandraStatus) {
1501         StorageOperationStatus result;
1502         switch (cassandraStatus) {
1503             case OK:
1504                 result = StorageOperationStatus.OK;
1505                 break;
1506             case NOT_FOUND:
1507                 result = StorageOperationStatus.NOT_FOUND;
1508                 break;
1509             case CLUSTER_NOT_CONNECTED:
1510             case KEYSPACE_NOT_CONNECTED:
1511                 result = StorageOperationStatus.CONNECTION_FAILURE;
1512                 break;
1513             default:
1514                 result = StorageOperationStatus.GENERAL_ERROR;
1515                 break;
1516         }
1517         return result;
1518     }
1519     
1520     
1521     public ResponseFormat getResponseFormat(ComponentException exception) {
1522         ResponseFormat responseFormat = exception.getResponseFormat();
1523         if (responseFormat != null) {
1524             return responseFormat;
1525         }
1526         return getResponseFormat(exception.getActionStatus(), exception.getParams());
1527     }
1528     public ActionStatus convertFromStorageResponseForRelationshipType(
1529             StorageOperationStatus storageResponse) {
1530         ActionStatus responseEnum;
1531
1532         switch (storageResponse) {
1533             case OK:
1534                 responseEnum = ActionStatus.OK;
1535                 break;
1536             case CONNECTION_FAILURE:
1537             case GRAPH_IS_LOCK:
1538                 responseEnum = ActionStatus.GENERAL_ERROR;
1539                 break;
1540             case BAD_REQUEST:
1541                 responseEnum = ActionStatus.INVALID_CONTENT;
1542                 break;
1543             case ENTITY_ALREADY_EXISTS:
1544                 responseEnum = ActionStatus.RELATIONSHIP_TYPE_ALREADY_EXIST;
1545                 break;
1546             case SCHEMA_VIOLATION:
1547                 responseEnum = ActionStatus.RELATIONSHIP_TYPE_ALREADY_EXIST;
1548                 break;
1549             default:
1550                 responseEnum = ActionStatus.GENERAL_ERROR;
1551                 break;
1552         }
1553         log.debug(CONVERT_STORAGE_RESPONSE_TO_ACTION_RESPONSE, storageResponse, responseEnum);
1554         return responseEnum;
1555     }
1556 }