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