Fix artifact name invalid error message
[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... params) {
408         ResponseFormat responseFormat;
409         switch (actionStatus) {
410             case RESOURCE_NOT_FOUND:
411             case ARTIFACT_NOT_FOUND:
412                 responseFormat = getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, params);
413                 break;
414             case ARTIFACT_NAME_INVALID:
415                 responseFormat = getResponseFormat(ActionStatus.ARTIFACT_NAME_INVALID, params);
416                 break;
417             default:
418                 responseFormat = getResponseFormat(actionStatus);
419                 break;
420         }
421         return responseFormat;
422     }
423
424     public ResponseFormat getInvalidContentErrorAndAudit(User user, AuditingActionEnum actionEnum) {
425         ResponseFormat responseFormat = responseFormatManager.getResponseFormat(ActionStatus.INVALID_CONTENT);
426         log.debug(AUDIT_BEFORE_SENDING_RESPONSE);
427         auditAdminUserAction(actionEnum, user, null, null, responseFormat);
428         return responseFormat;
429     }
430
431     public ResponseFormat getInvalidContentErrorAndAudit(User user, String resourceName, AuditingActionEnum actionEnum) {
432         ResponseFormat responseFormat = responseFormatManager.getResponseFormat(ActionStatus.INVALID_CONTENT);
433         log.debug(AUDIT_BEFORE_SENDING_RESPONSE);
434         auditResource(responseFormat, user, resourceName, actionEnum);
435         return responseFormat;
436     }
437
438     public ResponseFormat getInvalidContentErrorForConsumerAndAudit(User user, ConsumerDefinition consumer, AuditingActionEnum actionEnum) {
439         ResponseFormat responseFormat = responseFormatManager.getResponseFormat(ActionStatus.INVALID_CONTENT);
440         log.debug(AUDIT_BEFORE_SENDING_RESPONSE);
441         auditConsumerCredentialsEvent(actionEnum, consumer, responseFormat, user);
442         return responseFormat;
443     }
444
445     private ResponseFormat getInvalidContentErrorAndAuditComponent(User user, AuditingActionEnum actionEnum, ComponentTypeEnum typeEnum) {
446         ResponseFormat responseFormat = responseFormatManager.getResponseFormat(ActionStatus.INVALID_CONTENT);
447         log.debug(AUDIT_BEFORE_SENDING_RESPONSE);
448         auditComponentAdmin(responseFormat, user, null, actionEnum, typeEnum);
449         return responseFormat;
450     }
451
452     public void auditResource(ResponseFormat responseFormat, User modifier, Resource resource, AuditingActionEnum actionEnum,
453                               ResourceVersionInfo prevResFields) {
454         auditResource(responseFormat, modifier, resource, resource.getName(), actionEnum, prevResFields, null, null);
455     }
456
457     public void auditResource(ResponseFormat responseFormat, User modifier, String resourceName, AuditingActionEnum actionEnum) {
458         auditResource(responseFormat, modifier, null, resourceName, actionEnum);
459     }
460
461     public void auditResource(ResponseFormat responseFormat, User modifier, Resource resource, AuditingActionEnum actionEnum) {
462         auditResource(responseFormat, modifier, resource, resource.getName(), actionEnum);
463     }
464
465     public void auditResource(ResponseFormat responseFormat, User modifier, Resource resource, String resourceName, AuditingActionEnum actionEnum) {
466         auditResource(responseFormat, modifier, resource, resourceName, actionEnum, ResourceVersionInfo.newBuilder().build(), null, null);
467     }
468
469     public void auditResource(ResponseFormat responseFormat, User modifier, Resource resource, String resourceName, AuditingActionEnum actionEnum,
470                               ResourceVersionInfo prevResFields, String currentArtifactUuid, ArtifactDefinition artifactDefinition) {
471         if (actionEnum != null) {
472             int status = responseFormat.getStatus();
473             String uuid = null;
474             String resourceCurrVersion = null;
475             String resourceCurrState = null;
476             String invariantUUID = null;
477             String resourceType = ComponentTypeEnum.RESOURCE.getValue();
478             String toscaNodeType = null;
479             log.trace(INSIDE_AUDITING_FOR_AUDIT_ACTION, actionEnum);
480             String message = getMessageString(responseFormat);
481             String artifactData = buildAuditingArtifactData(artifactDefinition);
482             if (resource != null) {
483                 resourceName = resource.getName();
484                 resourceCurrVersion = resource.getVersion();
485                 if (resource.getLifecycleState() != null) {
486                     resourceCurrState = resource.getLifecycleState().name();
487                 }
488                 if (resource.getResourceType() != null) {
489                     resourceType = resource.getResourceType().name();
490                 }
491                 invariantUUID = resource.getInvariantUUID();
492                 uuid = resource.getUUID();
493                 toscaNodeType = resource.getToscaResourceName();
494             }
495             AuditEventFactory factory = AuditResourceEventFactoryManager.createResourceEventFactory(actionEnum,
496                 CommonAuditData.newBuilder().status(status).description(message).requestId(ThreadLocalsHolder.getUuid()).serviceInstanceId(uuid)
497                     .build(), new ResourceCommonInfo(resourceName, resourceType), prevResFields,
498                 ResourceVersionInfo.newBuilder().artifactUuid(currentArtifactUuid).state(resourceCurrState).version(resourceCurrVersion).build(),
499                 invariantUUID, modifier, artifactData, null, null, toscaNodeType);
500             getAuditingManager().auditEvent(factory);
501         }
502     }
503
504     private String getMessageString(ResponseFormat responseFormat) {
505         String message = "";
506         if (responseFormat.getMessageId() != null) {
507             message = responseFormat.getMessageId() + ": ";
508         }
509         message += responseFormat.getFormattedMessage();
510         return message;
511     }
512
513     public void auditDistributionDownload(ResponseFormat responseFormat, DistributionData distributionData) {
514         log.trace("Inside auditing");
515         int status = responseFormat.getStatus();
516         String message = getMessageString(responseFormat);
517         AuditDistributionDownloadEventFactory factory = new AuditDistributionDownloadEventFactory(
518             CommonAuditData.newBuilder().status(status).description(message).requestId(ThreadLocalsHolder.getUuid()).build(), distributionData);
519         getAuditingManager().auditEvent(factory);
520     }
521
522     public void auditExternalGetAsset(ResponseFormat responseFormat, AuditingActionEnum actionEnum, DistributionData distributionData,
523                                       ResourceCommonInfo resourceCommonInfo, String requestId, String serviceInstanceId) {
524         log.trace(INSIDE_AUDITING_FOR_AUDIT_ACTION, actionEnum);
525         AuditEventFactory factory = new AuditAssetExternalApiEventFactory(actionEnum,
526             CommonAuditData.newBuilder().status(responseFormat.getStatus()).description(getMessageString(responseFormat)).requestId(requestId)
527                 .serviceInstanceId(serviceInstanceId).build(), resourceCommonInfo, distributionData);
528         getAuditingManager().auditEvent(factory);
529     }
530
531     public void auditExternalGetAssetList(ResponseFormat responseFormat, AuditingActionEnum actionEnum, DistributionData distributionData,
532                                           String requestId) {
533         log.trace(INSIDE_AUDITING_FOR_AUDIT_ACTION, actionEnum);
534         AuditEventFactory factory = new AuditAssetListExternalApiEventFactory(actionEnum,
535             CommonAuditData.newBuilder().status(responseFormat.getStatus()).description(getMessageString(responseFormat)).requestId(requestId)
536                 .build(), distributionData);
537         getAuditingManager().auditEvent(factory);
538     }
539
540     public void auditChangeLifecycleAction(ResponseFormat responseFormat, ComponentTypeEnum componentType, String requestId, Component component,
541                                            Component responseObject, DistributionData distributionData, User modifier) {
542         String invariantUuid = "";
543         String serviceInstanceId = "";
544         ResourceVersionInfo currResourceVersionInfo = null;
545         ResourceVersionInfo prevResourceVersionInfo = null;
546         ResourceCommonInfo resourceCommonInfo = new ResourceCommonInfo(componentType.getValue());
547         if (component != null) {
548             prevResourceVersionInfo = buildResourceVersionInfoFromComponent(component);
549             resourceCommonInfo.setResourceName(component.getName());
550         }
551         if (responseObject != null) {
552             currResourceVersionInfo = buildResourceVersionInfoFromComponent(responseObject);
553             invariantUuid = responseObject.getInvariantUUID();
554             serviceInstanceId = responseObject.getUUID();
555         } else if (component != null) {
556             currResourceVersionInfo = buildResourceVersionInfoFromComponent(component);
557             invariantUuid = component.getInvariantUUID();
558             serviceInstanceId = component.getUUID();
559         }
560         if (prevResourceVersionInfo == null) {
561             prevResourceVersionInfo = ResourceVersionInfo.newBuilder().build();
562         }
563         if (currResourceVersionInfo == null) {
564             currResourceVersionInfo = ResourceVersionInfo.newBuilder().build();
565         }
566         AuditEventFactory factory = new AuditChangeLifecycleExternalApiEventFactory(
567             CommonAuditData.newBuilder().serviceInstanceId(serviceInstanceId).requestId(requestId).description(getMessageString(responseFormat))
568                 .status(responseFormat.getStatus()).build(), resourceCommonInfo, distributionData, prevResourceVersionInfo, currResourceVersionInfo,
569             invariantUuid, modifier);
570         getAuditingManager().auditEvent(factory);
571     }
572
573     private ResourceVersionInfo buildResourceVersionInfoFromComponent(Component component) {
574         return ResourceVersionInfo.newBuilder().version(component.getVersion()).state(component.getLifecycleState().name()).build();
575     }
576
577     public void auditExternalCrudApi(ResponseFormat responseFormat, AuditingActionEnum actionEnum, ResourceCommonInfo resourceCommonInfo,
578                                      HttpServletRequest request, ArtifactDefinition artifactDefinition, String artifactUuid) {
579         log.trace(INSIDE_AUDITING_FOR_AUDIT_ACTION, actionEnum);
580         ResourceVersionInfo currResourceVersionInfo;
581         User modifier = new User();
582         modifier.setUserId(request.getHeader(Constants.USER_ID_HEADER));
583         String artifactData = "";
584         DistributionData distributionData = new DistributionData(request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER), request.getRequestURI());
585         String requestId = request.getHeader(Constants.X_ECOMP_REQUEST_ID_HEADER);
586         if (artifactDefinition == null) {
587             currResourceVersionInfo = ResourceVersionInfo.newBuilder().artifactUuid(artifactUuid).build();
588         } else {
589             currResourceVersionInfo = ResourceVersionInfo.newBuilder().artifactUuid(artifactDefinition.getArtifactUUID())
590                 .version(artifactDefinition.getArtifactVersion()).build();
591             artifactData = buildAuditingArtifactData(artifactDefinition);
592             modifier.setUserId(artifactDefinition.getUserIdLastUpdater());
593         }
594         AuditEventFactory factory = new AuditCrudExternalApiArtifactEventFactory(actionEnum,
595             CommonAuditData.newBuilder().status(responseFormat.getStatus()).description(getMessageString(responseFormat)).requestId(requestId)
596                 .build(), resourceCommonInfo, distributionData, ResourceVersionInfo.newBuilder().build(), currResourceVersionInfo, null, modifier,
597             artifactData);
598         getAuditingManager().auditEvent(factory);
599     }
600
601     public boolean isExternalApiEvent(AuditingActionEnum auditingActionEnum) {
602         return auditingActionEnum != null && auditingActionEnum.getAuditingEsType().equals(AuditingTypesConstants.EXTERNAL_API_EVENT_TYPE);
603     }
604
605     public void auditCreateResourceExternalApi(ResponseFormat responseFormat, ResourceCommonInfo resourceCommonInfo, HttpServletRequest request,
606                                                Resource resource) {
607         String invariantUuid = null;
608         String serviceInstanceId = null;
609         User modifier = new User();
610         modifier.setUserId(request.getHeader(Constants.USER_ID_HEADER));
611         DistributionData distributionData = new DistributionData(request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER), request.getRequestURI());
612         String requestId = request.getHeader(Constants.X_ECOMP_REQUEST_ID_HEADER);
613         ResourceVersionInfo currResourceVersionInfo;
614         if (resource != null) {
615             currResourceVersionInfo = ResourceVersionInfo.newBuilder().state(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())
616                 .version(ImportUtils.Constants.FIRST_NON_CERTIFIED_VERSION).build();
617             resourceCommonInfo.setResourceName(resource.getName());
618             invariantUuid = resource.getInvariantUUID();
619             serviceInstanceId = resource.getUUID();
620         } else {
621             currResourceVersionInfo = ResourceVersionInfo.newBuilder().build();
622         }
623         AuditEventFactory factory = new AuditCreateResourceExternalApiEventFactory(
624             CommonAuditData.newBuilder().status(responseFormat.getStatus()).description(getMessageString(responseFormat)).requestId(requestId)
625                 .serviceInstanceId(serviceInstanceId).build(), resourceCommonInfo, distributionData, currResourceVersionInfo, invariantUuid,
626             modifier);
627         getAuditingManager().auditEvent(factory);
628     }
629
630     public void auditCreateServiceExternalApi(ResponseFormat responseFormat, HttpServletRequest request, Component service) {
631         String invariantUuid = null;
632         String serviceInstanceId = null;
633         User modifier = new User();
634         modifier.setUserId(request.getHeader(Constants.USER_ID_HEADER));
635         DistributionData distributionData = new DistributionData(request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER), request.getRequestURI());
636         String requestId = request.getHeader(Constants.X_ECOMP_REQUEST_ID_HEADER);
637         if (null != service) {
638             invariantUuid = service.getInvariantUUID();
639             serviceInstanceId = service.getUUID();
640         }
641         AuditEventFactory factory = new AuditCreateServiceExternalApiEventFactory(
642             CommonAuditData.newBuilder().status(responseFormat.getStatus()).description(getMessageString(responseFormat)).requestId(requestId)
643                 .serviceInstanceId(serviceInstanceId).build(), new ResourceCommonInfo(ComponentTypeEnum.SERVICE.name()), distributionData,
644             invariantUuid, modifier);
645         getAuditingManager().auditEvent(factory);
646     }
647
648     public void auditExternalActivateService(ResponseFormat responseFormat, DistributionData distributionData, String requestId,
649                                              String serviceInstanceUuid, User modifier) {
650         AuditEventFactory factory = new AuditActivateServiceExternalApiEventFactory(
651             CommonAuditData.newBuilder().serviceInstanceId(serviceInstanceUuid).description(getMessageString(responseFormat))
652                 .status(responseFormat.getStatus()).requestId(requestId).build(), new ResourceCommonInfo(ComponentTypeEnum.SERVICE.name()),
653             distributionData, "", modifier);
654         getAuditingManager().auditEvent(factory);
655     }
656
657     public void auditExternalDownloadArtifact(ResponseFormat responseFormat, ResourceCommonInfo resourceCommonInfo, DistributionData distributionData,
658                                               String requestId, String currArtifactUuid, String userId) {
659         User modifier = new User();
660         modifier.setUserId(userId);
661         AuditEventFactory factory = new AuditDownloadArtifactExternalApiEventFactory(
662             CommonAuditData.newBuilder().description(getMessageString(responseFormat)).status(responseFormat.getStatus()).requestId(requestId)
663                 .build(), resourceCommonInfo, distributionData, ResourceVersionInfo.newBuilder().artifactUuid(currArtifactUuid).build(), modifier);
664         getAuditingManager().auditEvent(factory);
665     }
666
667     private String buildAuditingArtifactData(ArtifactDefinition artifactDefinition) {
668         StringBuilder sb = new StringBuilder();
669         if (artifactDefinition != null) {
670             sb.append(artifactDefinition.getArtifactGroupType().getType()).append(",").append("'").append(artifactDefinition.getArtifactLabel())
671                 .append("'").append(",").append(artifactDefinition.getArtifactType()).append(",").append(artifactDefinition.getArtifactName())
672                 .append(",").append(artifactDefinition.getTimeout()).append(",").append(artifactDefinition.getEsId());
673             sb.append(",");
674             sb.append(artifactDefinition.getArtifactVersion() != null ? artifactDefinition.getArtifactVersion() : " ");
675             sb.append(",");
676             sb.append(artifactDefinition.getArtifactUUID() != null ? artifactDefinition.getArtifactUUID() : " ");
677         }
678         return sb.toString();
679     }
680
681     public void auditCategory(ResponseFormat responseFormat, User modifier, String categoryName, String subCategoryName, String groupingName,
682                               AuditingActionEnum actionEnum, String componentType) {
683         log.trace(INSIDE_AUDITING_FOR_AUDIT_ACTION, actionEnum);
684         AuditEventFactory factory = new AuditCategoryEventFactory(actionEnum,
685             CommonAuditData.newBuilder().description(getMessageString(responseFormat)).status(responseFormat.getStatus())
686                 .requestId(ThreadLocalsHolder.getUuid()).build(), modifier, categoryName, subCategoryName, groupingName, componentType);
687         getAuditingManager().auditEvent(factory);
688     }
689
690     public ActionStatus convertFromStorageResponse(StorageOperationStatus storageResponse) {
691         return convertFromStorageResponse(storageResponse, ComponentTypeEnum.RESOURCE);
692     }
693
694     public ActionStatus convertFromStorageResponse(StorageOperationStatus storageResponse, ComponentTypeEnum type) {
695         ActionStatus responseEnum = ActionStatus.GENERAL_ERROR;
696         if (storageResponse == null) {
697             return responseEnum;
698         }
699         switch (storageResponse) {
700             case OK:
701                 responseEnum = ActionStatus.OK;
702                 break;
703             case CONNECTION_FAILURE:
704             case GRAPH_IS_LOCK:
705                 responseEnum = ActionStatus.GENERAL_ERROR;
706                 break;
707             case BAD_REQUEST:
708                 responseEnum = ActionStatus.INVALID_CONTENT;
709                 break;
710             case ENTITY_ALREADY_EXISTS:
711                 responseEnum = ActionStatus.COMPONENT_NAME_ALREADY_EXIST;
712                 break;
713             case PARENT_RESOURCE_NOT_FOUND:
714                 responseEnum = ActionStatus.PARENT_RESOURCE_NOT_FOUND;
715                 break;
716             case MULTIPLE_PARENT_RESOURCE_FOUND:
717                 responseEnum = ActionStatus.MULTIPLE_PARENT_RESOURCE_FOUND;
718                 break;
719             case NOT_FOUND:
720                 if (ComponentTypeEnum.RESOURCE == type) {
721                     responseEnum = ActionStatus.RESOURCE_NOT_FOUND;
722                 } else if (ComponentTypeEnum.PRODUCT == type) {
723                     responseEnum = ActionStatus.PRODUCT_NOT_FOUND;
724                 } else {
725                     responseEnum = ActionStatus.SERVICE_NOT_FOUND;
726                 }
727                 break;
728             case FAILED_TO_LOCK_ELEMENT:
729                 responseEnum = ActionStatus.COMPONENT_IN_USE;
730                 break;
731             case ARTIFACT_NOT_FOUND:
732                 responseEnum = ActionStatus.ARTIFACT_NOT_FOUND;
733                 break;
734             case DISTR_ENVIRONMENT_NOT_AVAILABLE:
735                 responseEnum = ActionStatus.DISTRIBUTION_ENVIRONMENT_NOT_AVAILABLE;
736                 break;
737             case DISTR_ENVIRONMENT_NOT_FOUND:
738                 responseEnum = ActionStatus.DISTRIBUTION_ENVIRONMENT_NOT_FOUND;
739                 break;
740             case DISTR_ENVIRONMENT_SENT_IS_INVALID:
741                 responseEnum = ActionStatus.DISTRIBUTION_ENVIRONMENT_INVALID;
742                 break;
743             case INVALID_TYPE:
744                 responseEnum = ActionStatus.INVALID_CONTENT;
745                 break;
746             case INVALID_VALUE:
747                 responseEnum = ActionStatus.INVALID_CONTENT;
748                 break;
749             case CSAR_NOT_FOUND:
750                 responseEnum = ActionStatus.CSAR_NOT_FOUND;
751                 break;
752             case PROPERTY_NAME_ALREADY_EXISTS:
753                 responseEnum = ActionStatus.PROPERTY_NAME_ALREADY_EXISTS;
754                 break;
755             case MATCH_NOT_FOUND:
756                 responseEnum = ActionStatus.COMPONENT_SUB_CATEGORY_NOT_FOUND_FOR_CATEGORY;
757                 break;
758             case CATEGORY_NOT_FOUND:
759                 responseEnum = ActionStatus.COMPONENT_CATEGORY_NOT_FOUND;
760                 break;
761             case INVALID_PROPERTY:
762                 responseEnum = ActionStatus.INVALID_PROPERTY;
763                 break;
764             case COMPONENT_IS_ARCHIVED:
765                 responseEnum = ActionStatus.COMPONENT_IS_ARCHIVED;
766                 break;
767             case DECLARED_INPUT_USED_BY_OPERATION:
768                 responseEnum = ActionStatus.DECLARED_INPUT_USED_BY_OPERATION;
769                 break;
770             default:
771                 responseEnum = ActionStatus.GENERAL_ERROR;
772                 break;
773         }
774         log.debug(CONVERT_STORAGE_RESPONSE_TO_ACTION_RESPONSE, storageResponse, responseEnum);
775         return responseEnum;
776     }
777
778     public ActionStatus convertFromToscaError(ToscaError toscaError) {
779         ActionStatus responseEnum = ActionStatus.GENERAL_ERROR;
780         if (toscaError == null) {
781             return responseEnum;
782         }
783         switch (toscaError) {// TODO match errors
784             case NODE_TYPE_CAPABILITY_ERROR:
785             case NOT_SUPPORTED_TOSCA_TYPE:
786             case NODE_TYPE_REQUIREMENT_ERROR:
787                 responseEnum = ActionStatus.INVALID_CONTENT;
788                 break;
789             default:
790                 responseEnum = ActionStatus.GENERAL_ERROR;
791                 break;
792         }
793         return responseEnum;
794     }
795
796     public ActionStatus convertFromStorageResponseForCapabilityType(StorageOperationStatus storageResponse) {
797         ActionStatus responseEnum;
798         switch (storageResponse) {
799             case OK:
800                 responseEnum = ActionStatus.OK;
801                 break;
802             case CONNECTION_FAILURE:
803             case GRAPH_IS_LOCK:
804                 responseEnum = ActionStatus.GENERAL_ERROR;
805                 break;
806             case BAD_REQUEST:
807                 responseEnum = ActionStatus.INVALID_CONTENT;
808                 break;
809             case ENTITY_ALREADY_EXISTS:
810                 responseEnum = ActionStatus.CAPABILITY_TYPE_ALREADY_EXIST;
811                 break;
812             case SCHEMA_VIOLATION:
813                 responseEnum = ActionStatus.CAPABILITY_TYPE_ALREADY_EXIST;
814                 break;
815             default:
816                 responseEnum = ActionStatus.GENERAL_ERROR;
817                 break;
818         }
819         log.debug(CONVERT_STORAGE_RESPONSE_TO_ACTION_RESPONSE, storageResponse, responseEnum);
820         return responseEnum;
821     }
822
823     public ActionStatus convertFromStorageResponseForLifecycleType(StorageOperationStatus storageResponse) {
824         ActionStatus responseEnum;
825         switch (storageResponse) {
826             case OK:
827                 responseEnum = ActionStatus.OK;
828                 break;
829             case CONNECTION_FAILURE:
830             case GRAPH_IS_LOCK:
831                 responseEnum = ActionStatus.GENERAL_ERROR;
832                 break;
833             case BAD_REQUEST:
834                 responseEnum = ActionStatus.INVALID_CONTENT;
835                 break;
836             case ENTITY_ALREADY_EXISTS:
837                 responseEnum = ActionStatus.LIFECYCLE_TYPE_ALREADY_EXIST;
838                 break;
839             case SCHEMA_VIOLATION:
840                 responseEnum = ActionStatus.LIFECYCLE_TYPE_ALREADY_EXIST;
841                 break;
842             default:
843                 responseEnum = ActionStatus.GENERAL_ERROR;
844                 break;
845         }
846         log.debug(CONVERT_STORAGE_RESPONSE_TO_ACTION_RESPONSE, storageResponse, responseEnum);
847         return responseEnum;
848     }
849
850     public ActionStatus convertFromStorageResponseForResourceInstance(StorageOperationStatus storageResponse, boolean isRelation) {
851         ActionStatus responseEnum;
852         switch (storageResponse) {
853             case OK:
854                 responseEnum = ActionStatus.OK;
855                 break;
856             case INVALID_ID:
857                 responseEnum = ActionStatus.RESOURCE_INSTANCE_BAD_REQUEST;
858                 break;
859             case INVALID_PROPERTY:
860                 responseEnum = ActionStatus.INVALID_PROPERTY;
861                 break;
862             case GRAPH_IS_LOCK:
863                 responseEnum = ActionStatus.GENERAL_ERROR;
864                 break;
865             case BAD_REQUEST:
866                 responseEnum = ActionStatus.INVALID_CONTENT;
867                 break;
868             case MATCH_NOT_FOUND:
869                 responseEnum = ActionStatus.RESOURCE_INSTANCE_MATCH_NOT_FOUND;
870                 break;
871             case SCHEMA_VIOLATION:
872                 responseEnum = ActionStatus.RESOURCE_INSTANCE_ALREADY_EXIST;
873                 break;
874             case NOT_FOUND:
875                 if (isRelation) {
876                     responseEnum = ActionStatus.RESOURCE_INSTANCE_RELATION_NOT_FOUND;
877                 } else {
878                     responseEnum = ActionStatus.RESOURCE_INSTANCE_NOT_FOUND;
879                 }
880                 break;
881             default:
882                 responseEnum = ActionStatus.GENERAL_ERROR;
883                 break;
884         }
885         log.debug(CONVERT_STORAGE_RESPONSE_TO_ACTION_RESPONSE, storageResponse, responseEnum);
886         return responseEnum;
887     }
888
889     public ResponseFormat getResponseFormatForResourceInstance(ActionStatus actionStatus, String serviceName, String resourceInstanceName) {
890         ResponseFormat responseFormat;
891         if (actionStatus == ActionStatus.RESOURCE_INSTANCE_NOT_FOUND) {
892             responseFormat = getResponseFormat(actionStatus, resourceInstanceName);
893         } else {
894             responseFormat = getResponseFormat(actionStatus, serviceName);
895         }
896         return responseFormat;
897     }
898
899     public ResponseFormat getResponseFormatForResourceInstanceProperty(ActionStatus actionStatus, String resourceInstanceName) {
900         ResponseFormat responseFormat;
901         if (actionStatus == ActionStatus.RESOURCE_INSTANCE_NOT_FOUND) {
902             responseFormat = getResponseFormat(actionStatus, resourceInstanceName);
903         } else {
904             responseFormat = getResponseFormat(actionStatus);
905         }
906         return responseFormat;
907     }
908
909     public ActionStatus convertFromStorageResponseForResourceInstanceProperty(StorageOperationStatus storageResponse) {
910         ActionStatus responseEnum;
911         switch (storageResponse) {
912             case OK:
913                 responseEnum = ActionStatus.OK;
914                 break;
915             case INVALID_ID:
916                 responseEnum = ActionStatus.RESOURCE_INSTANCE_BAD_REQUEST;
917                 break;
918             case GRAPH_IS_LOCK:
919                 responseEnum = ActionStatus.GENERAL_ERROR;
920                 break;
921             case BAD_REQUEST:
922                 responseEnum = ActionStatus.INVALID_CONTENT;
923                 break;
924             case MATCH_NOT_FOUND:
925                 responseEnum = ActionStatus.RESOURCE_INSTANCE_MATCH_NOT_FOUND;
926                 break;
927             case SCHEMA_VIOLATION:
928                 responseEnum = ActionStatus.RESOURCE_INSTANCE_ALREADY_EXIST;
929                 break;
930             case NOT_FOUND:
931                 responseEnum = ActionStatus.RESOURCE_INSTANCE_NOT_FOUND;
932                 break;
933             default:
934                 responseEnum = ActionStatus.GENERAL_ERROR;
935                 break;
936         }
937         log.debug(CONVERT_STORAGE_RESPONSE_TO_ACTION_RESPONSE, storageResponse, responseEnum);
938         return responseEnum;
939     }
940
941     public void auditComponent(ResponseFormat responseFormat, User modifier, Component component, AuditingActionEnum actionEnum,
942                                ResourceCommonInfo resourceCommonInfo, ResourceVersionInfo prevComponent, String comment) {
943         auditComponent(responseFormat, modifier, component, actionEnum, resourceCommonInfo, prevComponent, null, comment, null, null);
944     }
945
946     public void auditComponentAdmin(ResponseFormat responseFormat, User modifier, Component component, AuditingActionEnum actionEnum,
947                                     ComponentTypeEnum typeEnum) {
948         auditComponent(responseFormat, modifier, component, actionEnum, new ResourceCommonInfo(typeEnum.getValue()),
949             ResourceVersionInfo.newBuilder().build());
950     }
951
952     public void auditComponentAdmin(ResponseFormat responseFormat, User modifier, Component component, AuditingActionEnum actionEnum,
953                                     ComponentTypeEnum typeEnum, String comment) {
954         auditComponent(responseFormat, modifier, component, actionEnum, new ResourceCommonInfo(typeEnum.getValue()),
955             ResourceVersionInfo.newBuilder().build(), null, comment, null, null);
956     }
957
958     public void auditComponentAdmin(ResponseFormat responseFormat, User modifier, Component component, AuditingActionEnum actionEnum,
959                                     ComponentTypeEnum typeEnum, ResourceVersionInfo prevComponent) {
960         auditComponent(responseFormat, modifier, component, actionEnum, new ResourceCommonInfo(typeEnum.getValue()), prevComponent);
961     }
962
963     public void auditComponent(ResponseFormat responseFormat, User modifier, Component component, AuditingActionEnum actionEnum,
964                                ResourceCommonInfo resourceCommonInfo, ResourceVersionInfo prevComponent) {
965         auditComponent(responseFormat, modifier, component, actionEnum, resourceCommonInfo, prevComponent, null, null, null, null);
966     }
967
968     public void auditComponent(ResponseFormat responseFormat, User modifier, AuditingActionEnum actionEnum, ResourceCommonInfo resourceCommonInfo,
969                                String comment) {
970         auditComponent(responseFormat, modifier, null, actionEnum, resourceCommonInfo, ResourceVersionInfo.newBuilder().build(), null, comment, null,
971             null);
972     }
973
974     public void auditComponent(ResponseFormat responseFormat, User modifier, Component component, AuditingActionEnum actionEnum,
975                                ResourceCommonInfo resourceCommonInfo, ResourceVersionInfo prevComponent, ResourceVersionInfo currComponent) {
976         auditComponent(responseFormat, modifier, component, actionEnum, resourceCommonInfo, prevComponent, currComponent, null, null, null);
977     }
978
979     public void auditComponent(ResponseFormat responseFormat, User modifier, Component component, AuditingActionEnum actionEnum,
980                                ResourceCommonInfo resourceCommonInfo, ResourceVersionInfo prevComponent, ResourceVersionInfo currComponent,
981                                String comment, ArtifactDefinition artifactDefinition, String did) {
982         if (actionEnum != null) {
983             String uuid = null;
984             String currState = null;
985             String invariantUUID = null;
986             String currArtifactUid = null;
987             String currVersion = null;
988             String dcurrStatus = null;
989             log.trace(INSIDE_AUDITING_FOR_AUDIT_ACTION, actionEnum);
990             String message = getMessageString(responseFormat);
991             int status = responseFormat.getStatus();
992             String artifactData = buildAuditingArtifactData(artifactDefinition);
993             if (component != null) {
994                 // fields that are filled during creation and might still be empty
995                 if (component.getLifecycleState() != null) {
996                     currState = component.getLifecycleState().name();
997                 }
998                 uuid = component.getUUID();
999                 invariantUUID = component.getInvariantUUID();
1000                 currVersion = component.getVersion();
1001                 if (StringUtils.isEmpty(resourceCommonInfo.getResourceName())) {
1002                     resourceCommonInfo.setResourceName(component.getComponentMetadataDefinition().getMetadataDataDefinition().getName());
1003                 }
1004             }
1005             if (currComponent != null) {
1006                 currArtifactUid = currComponent.getArtifactUuid();
1007                 dcurrStatus = currComponent.getDistributionStatus();
1008                 if (currState == null) { //probably it was not set
1009                     currState = currComponent.getState();
1010                 }
1011                 if (currVersion == null) { //probably it was not set
1012                     currVersion = currComponent.getVersion();
1013                 }
1014             }
1015             AuditEventFactory factory = AuditResourceEventFactoryManager.createResourceEventFactory(actionEnum,
1016                 CommonAuditData.newBuilder().status(status).description(message).requestId(ThreadLocalsHolder.getUuid()).serviceInstanceId(uuid)
1017                     .build(), resourceCommonInfo, prevComponent,
1018                 ResourceVersionInfo.newBuilder().artifactUuid(currArtifactUid).state(currState).version(currVersion).distributionStatus(dcurrStatus)
1019                     .build(), invariantUUID, modifier, artifactData, comment, did, null);
1020             getAuditingManager().auditEvent(factory);
1021         }
1022     }
1023
1024     public void auditDistributionEngine(AuditingActionEnum action, String environmentName, DistributionTopicData distributionTopicData,
1025                                         String status) {
1026         auditDistributionEngine(action, environmentName, distributionTopicData, null, null, status);
1027     }
1028
1029     public void auditDistributionEngine(AuditingActionEnum action, String environmentName, DistributionTopicData distributionTopicData, String role,
1030                                         String apiKey, String status) {
1031         AuditEventFactory factory = AuditDistributionEngineEventFactoryManager
1032             .createDistributionEngineEventFactory(action, environmentName, distributionTopicData, role, apiKey, status);
1033         getAuditingManager().auditEvent(factory);
1034     }
1035
1036     public void auditEnvironmentEngine(AuditingActionEnum actionEnum, String environmentID, String environmentType, String action,
1037                                        String environmentName, String tenantContext) {
1038         AuditEventFactory factory = new AuditEcompOpEnvEventFactory(actionEnum, environmentID, environmentName, environmentType, action,
1039             tenantContext);
1040         audit.startAuditFetchLog(PARTNER_NAME, DmaapConsumer.class.getName());
1041         audit.logEntry(LogLevel.INFO, Severity.OK, null, MarkerFactory.getMarker(ONAPLogConstants.Markers.ENTRY.getName()), environmentID);
1042         getAuditingManager().auditEvent(factory, audit);
1043     }
1044
1045     public void auditDistributionNotification(String serviceUUID, String resourceName, String resourceType, String currVersion, User modifier,
1046                                               String environmentName, String currState, String topicName, String distributionId, String description,
1047                                               String status, String workloadContext, String tenant) {
1048         AuditEventFactory factory = new AuditDistributionNotificationEventFactory(
1049             CommonAuditData.newBuilder().serviceInstanceId(serviceUUID).status(status).description(description)
1050                 .requestId(ThreadLocalsHolder.getUuid()).build(), new ResourceCommonInfo(resourceName, resourceType),
1051             ResourceVersionInfo.newBuilder().state(currState).version(currVersion).build(), distributionId, modifier, topicName,
1052             new OperationalEnvAuditData(environmentName, workloadContext, tenant));
1053         getAuditingManager().auditEvent(factory);
1054     }
1055
1056     public void auditAuthEvent(String url, String user, String authStatus, String realm) {
1057         AuditEventFactory factory = new AuditAuthRequestEventFactory(CommonAuditData.newBuilder().requestId(ThreadLocalsHolder.getUuid()).build(),
1058             user, url, realm, authStatus);
1059         getAuditingManager().auditEvent(factory);
1060     }
1061
1062     public void auditDistributionStatusNotification(String distributionId, String consumerId, String topicName, String resourceUrl, String statusTime,
1063                                                     String status, String errorReason, LoggerSdcAudit audit) {
1064         AuditEventFactory factory = new AuditDistributionStatusEventFactory(
1065             CommonAuditData.newBuilder().description(errorReason).status(status).requestId(distributionId).build(),
1066             new DistributionData(consumerId, resourceUrl), distributionId, topicName, statusTime);
1067         getAuditingManager().auditEvent(factory, audit);
1068     }
1069
1070     public void auditGetUebCluster(String consumerId, String status, String description) {
1071         AuditEventFactory factory = new AuditGetUebClusterEventFactory(
1072             CommonAuditData.newBuilder().description(description).status(status).requestId(ThreadLocalsHolder.getUuid()).build(), consumerId);
1073         getAuditingManager().auditEvent(factory);
1074     }
1075
1076     public void auditMissingInstanceIdAsDistributionEngineEvent(AuditingActionEnum actionEnum, String status) {
1077         AuditEventFactory factory = AuditDistributionEngineEventFactoryManager
1078             .createDistributionEngineEventFactory(actionEnum, "", DistributionTopicData.newBuilder().build(), null, null, status);
1079         getAuditingManager().auditEvent(factory);
1080     }
1081
1082     public void auditRegisterOrUnRegisterEvent(AuditingActionEnum action, String consumerId, String apiPublicKey, String envName, String status,
1083                                                String distributionStatus, String notifTopicName, String statusTopicName) {
1084         String appliedStatus = !StringUtils.isEmpty(status) ? status : distributionStatus;
1085         AuditEventFactory factory = new AuditRegUnregDistributionEngineEventFactory(action,
1086             CommonAuditData.newBuilder().requestId(ThreadLocalsHolder.getUuid()).status(appliedStatus).build(),
1087             DistributionTopicData.newBuilder().statusTopic(statusTopicName).notificationTopic(notifTopicName).build(), consumerId, apiPublicKey,
1088             envName);
1089         getAuditingManager().auditEvent(factory);
1090     }
1091
1092     public void auditServiceDistributionDeployed(String serviceName, String serviceVersion, String serviceUUID, String distributionId, String status,
1093                                                  String desc, User modifier) {
1094         AuditEventFactory factory = new AuditDistributionDeployEventFactory(
1095             CommonAuditData.newBuilder().requestId(ThreadLocalsHolder.getUuid()).serviceInstanceId(serviceUUID).status(status).description(desc)
1096                 .build(), new ResourceCommonInfo(serviceName, "Service"), distributionId, modifier, serviceVersion);
1097         getAuditingManager().auditEvent(factory);
1098     }
1099
1100     public void auditConsumerCredentialsEvent(AuditingActionEnum actionEnum, ConsumerDefinition consumer, ResponseFormat responseFormat,
1101                                               User modifier) {
1102         AuditEventFactory factory = new AuditConsumerEventFactory(actionEnum,
1103             CommonAuditData.newBuilder().description(getMessageString(responseFormat)).status(responseFormat.getStatus())
1104                 .requestId(ThreadLocalsHolder.getUuid()).build(), modifier, consumer);
1105         getAuditingManager().auditEvent(factory);
1106     }
1107
1108     public void auditGetUsersList(User user, String details, ResponseFormat responseFormat) {
1109         AuditEventFactory factory = new AuditGetUsersListEventFactory(
1110             CommonAuditData.newBuilder().description(getMessageString(responseFormat)).status(responseFormat.getStatus())
1111                 .requestId(ThreadLocalsHolder.getUuid()).build(), user, details);
1112         getAuditingManager().auditEvent(factory);
1113     }
1114
1115     public void auditAdminUserActionAndThrowException(AuditingActionEnum actionEnum, User modifier, User userBefore, User userAfter,
1116                                                       ActionStatus status, String... params) {
1117         ResponseFormat responseFormat = getResponseFormat(status, params);
1118         auditAdminUserAction(actionEnum, modifier, userBefore, userAfter, responseFormat);
1119         throw new ByResponseFormatComponentException(responseFormat);
1120     }
1121
1122     public void auditAdminUserAction(AuditingActionEnum actionEnum, User modifier, User userBefore, User userAfter, ResponseFormat responseFormat) {
1123         AuditEventFactory factory = new AuditUserAdminEventFactory(actionEnum,
1124             CommonAuditData.newBuilder().description(getMessageString(responseFormat)).status(responseFormat.getStatus())
1125                 .requestId(ThreadLocalsHolder.getUuid()).build(), modifier, userBefore, userAfter);
1126         getAuditingManager().auditEvent(factory);
1127     }
1128
1129     public void auditUserAccess(User user, ActionStatus status, String... params) {
1130         auditUserAccess(user, getResponseFormat(status, params));
1131     }
1132
1133     public void auditUserAccess(User user, ResponseFormat responseFormat) {
1134         AuditEventFactory factory = new AuditUserAccessEventFactory(
1135             CommonAuditData.newBuilder().description(getMessageString(responseFormat)).status(responseFormat.getStatus())
1136                 .requestId(ThreadLocalsHolder.getUuid()).build(), user);
1137         getAuditingManager().auditEvent(factory);
1138     }
1139
1140     public void auditGetCategoryHierarchy(User user, String details, ResponseFormat responseFormat) {
1141         AuditEventFactory factory = new AuditGetCategoryHierarchyEventFactory(
1142             CommonAuditData.newBuilder().description(getMessageString(responseFormat)).status(responseFormat.getStatus())
1143                 .requestId(ThreadLocalsHolder.getUuid()).build(), user, details);
1144         getAuditingManager().auditEvent(factory);
1145     }
1146
1147     public ResponseFormat getResponseFormatByComponent(ActionStatus actionStatus, Component component, ComponentTypeEnum type) {
1148         if (component == null) {
1149             return getResponseFormat(actionStatus);
1150         }
1151         ResponseFormat responseFormat;
1152         switch (actionStatus) {
1153             case COMPONENT_VERSION_ALREADY_EXIST:
1154                 responseFormat = getResponseFormat(ActionStatus.COMPONENT_VERSION_ALREADY_EXIST, type.getValue(), component.getVersion());
1155                 break;
1156             case RESOURCE_NOT_FOUND:
1157                 responseFormat = getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND,
1158                     component.getComponentMetadataDefinition().getMetadataDataDefinition().getName());
1159                 break;
1160             case COMPONENT_NAME_ALREADY_EXIST:
1161                 responseFormat = getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, type.getValue(),
1162                     component.getComponentMetadataDefinition().getMetadataDataDefinition().getName());
1163                 break;
1164             case COMPONENT_IN_USE:
1165                 responseFormat = getResponseFormat(ActionStatus.COMPONENT_IN_USE, type.name().toLowerCase(), component.getUniqueId());
1166                 break;
1167             case SERVICE_DEPLOYMENT_ARTIFACT_NOT_FOUND:
1168                 responseFormat = getResponseFormat(ActionStatus.SERVICE_DEPLOYMENT_ARTIFACT_NOT_FOUND,
1169                     component.getComponentMetadataDefinition().getMetadataDataDefinition().getName());
1170                 break;
1171             default:
1172                 responseFormat = getResponseFormat(actionStatus);
1173                 break;
1174         }
1175         return responseFormat;
1176     }
1177
1178     public boolean validateStringNotEmpty(String value) {
1179         return value != null && !value.trim().isEmpty();
1180     }
1181
1182     public ActionStatus convertFromStorageResponseForAdditionalInformation(StorageOperationStatus storageResponse) {
1183         ActionStatus responseEnum;
1184         switch (storageResponse) {
1185             case OK:
1186                 responseEnum = ActionStatus.OK;
1187                 break;
1188             case ENTITY_ALREADY_EXISTS:
1189                 responseEnum = ActionStatus.COMPONENT_NAME_ALREADY_EXIST;
1190                 break;
1191             case INVALID_ID:
1192                 responseEnum = ActionStatus.ADDITIONAL_INFORMATION_NOT_FOUND;
1193                 break;
1194             default:
1195                 responseEnum = ActionStatus.GENERAL_ERROR;
1196                 break;
1197         }
1198         log.debug(CONVERT_STORAGE_RESPONSE_TO_ACTION_RESPONSE, storageResponse, responseEnum);
1199         return responseEnum;
1200     }
1201
1202     public ActionStatus convertFromResultStatusEnum(ResultStatusEnum resultStatus, JsonPresentationFields elementType) {
1203         ActionStatus responseEnum = ActionStatus.GENERAL_ERROR;
1204         switch (resultStatus) {
1205             case OK:
1206                 responseEnum = ActionStatus.OK;
1207                 break;
1208             case ELEMENT_NOT_FOUND:
1209                 if (elementType != null && elementType == JsonPresentationFields.PROPERTY) {
1210                     responseEnum = ActionStatus.PROPERTY_NOT_FOUND;
1211                 }
1212                 break;
1213             case INVALID_PROPERTY_DEFAULT_VALUE:
1214             case INVALID_PROPERTY_TYPE:
1215             case INVALID_PROPERTY_VALUE:
1216             case INVALID_PROPERTY_NAME:
1217             case MISSING_ENTRY_SCHEMA_TYPE:
1218                 responseEnum = ActionStatus.INVALID_PROPERTY;
1219                 break;
1220             case INVALID_ATTRIBUTE_NAME:
1221                 responseEnum = ActionStatus.INVALID_ATTRIBUTE;
1222                 break;
1223             default:
1224                 responseEnum = ActionStatus.GENERAL_ERROR;
1225                 break;
1226         }
1227         return responseEnum;
1228     }
1229
1230     public ResponseFormat getResponseFormatAdditionalProperty(ActionStatus actionStatus, AdditionalInfoParameterInfo additionalInfoParameterInfo,
1231                                                               NodeTypeEnum nodeType, AdditionalInformationEnum labelOrValue) {
1232         if (additionalInfoParameterInfo == null) {
1233             additionalInfoParameterInfo = new AdditionalInfoParameterInfo();
1234         }
1235         if (labelOrValue == null) {
1236             labelOrValue = AdditionalInformationEnum.None;
1237         }
1238         switch (actionStatus) {
1239             case COMPONENT_NAME_ALREADY_EXIST:
1240                 return getResponseFormat(actionStatus, "Additional parameter", additionalInfoParameterInfo.getKey());
1241             case ADDITIONAL_INFORMATION_EXCEEDS_LIMIT:
1242                 return getResponseFormat(actionStatus, labelOrValue.name().toLowerCase(),
1243                     ValidationUtils.ADDITIONAL_INFORMATION_KEY_MAX_LENGTH.toString());
1244             case ADDITIONAL_INFORMATION_MAX_NUMBER_REACHED:
1245                 return getResponseFormat(actionStatus, nodeType.name().toLowerCase());
1246             case ADDITIONAL_INFORMATION_EMPTY_STRING_NOT_ALLOWED:
1247                 return getResponseFormat(actionStatus);
1248             case ADDITIONAL_INFORMATION_KEY_NOT_ALLOWED_CHARACTERS:
1249                 return getResponseFormat(actionStatus);
1250             case ADDITIONAL_INFORMATION_VALUE_NOT_ALLOWED_CHARACTERS:
1251                 return getResponseFormat(actionStatus);
1252             case ADDITIONAL_INFORMATION_NOT_FOUND:
1253                 return getResponseFormat(actionStatus);
1254             default:
1255                 return getResponseFormat(actionStatus);
1256         }
1257     }
1258
1259     public ResponseFormat getResponseFormatAdditionalProperty(ActionStatus actionStatus) {
1260         return getResponseFormatAdditionalProperty(actionStatus, null, null, null);
1261     }
1262
1263     public ActionStatus convertFromStorageResponseForConsumer(StorageOperationStatus storageResponse) {
1264         ActionStatus responseEnum;
1265         switch (storageResponse) {
1266             case OK:
1267                 responseEnum = ActionStatus.OK;
1268                 break;
1269             case CONNECTION_FAILURE:
1270             case GRAPH_IS_LOCK:
1271                 responseEnum = ActionStatus.GENERAL_ERROR;
1272                 break;
1273             case BAD_REQUEST:
1274                 responseEnum = ActionStatus.INVALID_CONTENT;
1275                 break;
1276             case ENTITY_ALREADY_EXISTS:
1277                 responseEnum = ActionStatus.CONSUMER_ALREADY_EXISTS;
1278                 break;
1279             case SCHEMA_VIOLATION:
1280                 responseEnum = ActionStatus.CONSUMER_ALREADY_EXISTS;
1281                 break;
1282             case NOT_FOUND:
1283                 responseEnum = ActionStatus.ECOMP_USER_NOT_FOUND;
1284                 break;
1285             default:
1286                 responseEnum = ActionStatus.GENERAL_ERROR;
1287                 break;
1288         }
1289         log.debug(CONVERT_STORAGE_RESPONSE_TO_ACTION_RESPONSE, storageResponse, responseEnum);
1290         return responseEnum;
1291     }
1292
1293     public ActionStatus convertFromStorageResponseForGroupType(StorageOperationStatus storageResponse) {
1294         ActionStatus responseEnum;
1295         switch (storageResponse) {
1296             case OK:
1297                 responseEnum = ActionStatus.OK;
1298                 break;
1299             case CONNECTION_FAILURE:
1300             case GRAPH_IS_LOCK:
1301                 responseEnum = ActionStatus.GENERAL_ERROR;
1302                 break;
1303             case BAD_REQUEST:
1304                 responseEnum = ActionStatus.INVALID_CONTENT;
1305                 break;
1306             case ENTITY_ALREADY_EXISTS:
1307                 responseEnum = ActionStatus.GROUP_TYPE_ALREADY_EXIST;
1308                 break;
1309             case SCHEMA_VIOLATION:
1310                 responseEnum = ActionStatus.GROUP_TYPE_ALREADY_EXIST;
1311                 break;
1312             default:
1313                 responseEnum = ActionStatus.GENERAL_ERROR;
1314                 break;
1315         }
1316         log.debug(CONVERT_STORAGE_RESPONSE_TO_ACTION_RESPONSE, storageResponse, responseEnum);
1317         return responseEnum;
1318     }
1319
1320     public ActionStatus convertFromStorageResponseForPolicyType(StorageOperationStatus storageResponse) {
1321         ActionStatus responseEnum;
1322         switch (storageResponse) {
1323             case OK:
1324                 responseEnum = ActionStatus.OK;
1325                 break;
1326             case CONNECTION_FAILURE:
1327             case GRAPH_IS_LOCK:
1328                 responseEnum = ActionStatus.GENERAL_ERROR;
1329                 break;
1330             case BAD_REQUEST:
1331                 responseEnum = ActionStatus.INVALID_CONTENT;
1332                 break;
1333             case ENTITY_ALREADY_EXISTS:
1334                 responseEnum = ActionStatus.POLICY_TYPE_ALREADY_EXIST;
1335                 break;
1336             case SCHEMA_VIOLATION:
1337                 responseEnum = ActionStatus.POLICY_TYPE_ALREADY_EXIST;
1338                 break;
1339             default:
1340                 responseEnum = ActionStatus.GENERAL_ERROR;
1341                 break;
1342         }
1343         log.debug(CONVERT_STORAGE_RESPONSE_TO_ACTION_RESPONSE, storageResponse, responseEnum);
1344         return responseEnum;
1345     }
1346
1347     public ActionStatus convertFromStorageResponseForDataType(StorageOperationStatus storageResponse) {
1348         ActionStatus responseEnum;
1349         switch (storageResponse) {
1350             case OK:
1351                 responseEnum = ActionStatus.OK;
1352                 break;
1353             case CONNECTION_FAILURE:
1354             case GRAPH_IS_LOCK:
1355                 responseEnum = ActionStatus.GENERAL_ERROR;
1356                 break;
1357             case BAD_REQUEST:
1358                 responseEnum = ActionStatus.INVALID_CONTENT;
1359                 break;
1360             case ENTITY_ALREADY_EXISTS:
1361                 responseEnum = ActionStatus.DATA_TYPE_ALREADY_EXIST;
1362                 break;
1363             case SCHEMA_VIOLATION:
1364                 responseEnum = ActionStatus.DATA_TYPE_ALREADY_EXIST;
1365                 break;
1366             case CANNOT_UPDATE_EXISTING_ENTITY:
1367                 responseEnum = ActionStatus.DATA_TYPE_CANNOT_BE_UPDATED_BAD_REQUEST;
1368                 break;
1369             default:
1370                 responseEnum = ActionStatus.GENERAL_ERROR;
1371                 break;
1372         }
1373         log.debug(CONVERT_STORAGE_RESPONSE_TO_ACTION_RESPONSE, storageResponse, responseEnum);
1374         return responseEnum;
1375     }
1376
1377     public ResponseFormat getResponseFormatByGroupType(ActionStatus actionStatus, GroupTypeDefinition groupType) {
1378         if (groupType == null) {
1379             return getResponseFormat(actionStatus);
1380         }
1381         ResponseFormat responseFormat;
1382         switch (actionStatus) {
1383             case GROUP_MEMBER_EMPTY:
1384             case GROUP_TYPE_ALREADY_EXIST:
1385                 responseFormat = getResponseFormat(actionStatus, groupType.getType());
1386                 break;
1387             default:
1388                 responseFormat = getResponseFormat(actionStatus);
1389                 break;
1390         }
1391         return responseFormat;
1392     }
1393
1394     public ResponseFormat getResponseFormatByPolicyType(ActionStatus actionStatus, PolicyTypeDefinition policyType) {
1395         if (policyType == null) {
1396             return getResponseFormat(actionStatus);
1397         }
1398         ResponseFormat responseFormat;
1399         if (actionStatus == ActionStatus.POLICY_TYPE_ALREADY_EXIST) {
1400             responseFormat = getResponseFormat(actionStatus, policyType.getType());
1401         } else {
1402             responseFormat = getResponseFormat(actionStatus);
1403         }
1404         return responseFormat;
1405     }
1406
1407     public ResponseFormat getResponseFormatByDataType(ActionStatus actionStatus, DataTypeDefinition dataType, List<String> properties) {
1408         if (dataType == null) {
1409             return getResponseFormat(actionStatus);
1410         }
1411         ResponseFormat responseFormat;
1412         switch (actionStatus) {
1413             case DATA_TYPE_ALREADY_EXIST:
1414                 responseFormat = getResponseFormat(actionStatus, dataType.getName());
1415                 break;
1416             case DATA_TYPE_NOR_PROPERTIES_NEITHER_DERIVED_FROM:
1417                 responseFormat = getResponseFormat(actionStatus, dataType.getName());
1418                 break;
1419             case DATA_TYPE_PROPERTIES_CANNOT_BE_EMPTY:
1420                 responseFormat = getResponseFormat(actionStatus, dataType.getName());
1421                 break;
1422             case DATA_TYPE_PROPERTY_ALREADY_DEFINED_IN_ANCESTOR:
1423                 responseFormat = getResponseFormat(actionStatus, dataType.getName(), properties == null ? "" : String.valueOf(properties));
1424                 break;
1425             case DATA_TYPE_DERIVED_IS_MISSING:
1426                 responseFormat = getResponseFormat(actionStatus, dataType.getDerivedFromName());
1427                 break;
1428             case DATA_TYPE_DUPLICATE_PROPERTY:
1429                 responseFormat = getResponseFormat(actionStatus, dataType.getName());
1430                 break;
1431             case DATA_TYPE_PROEPRTY_CANNOT_HAVE_SAME_TYPE_OF_DATA_TYPE:
1432                 responseFormat = getResponseFormat(actionStatus, dataType.getName(), properties == null ? "" : String.valueOf(properties));
1433                 break;
1434             case DATA_TYPE_CANNOT_HAVE_PROPERTIES:
1435                 responseFormat = getResponseFormat(actionStatus, dataType.getName());
1436                 break;
1437             case DATA_TYPE_CANNOT_BE_UPDATED_BAD_REQUEST:
1438                 responseFormat = getResponseFormat(actionStatus, dataType.getName());
1439                 break;
1440             default:
1441                 responseFormat = getResponseFormat(actionStatus);
1442                 break;
1443         }
1444         return responseFormat;
1445     }
1446
1447     public StorageOperationStatus convertToStorageOperationStatus(CassandraOperationStatus cassandraStatus) {
1448         StorageOperationStatus result;
1449         switch (cassandraStatus) {
1450             case OK:
1451                 result = StorageOperationStatus.OK;
1452                 break;
1453             case NOT_FOUND:
1454                 result = StorageOperationStatus.NOT_FOUND;
1455                 break;
1456             case CLUSTER_NOT_CONNECTED:
1457             case KEYSPACE_NOT_CONNECTED:
1458                 result = StorageOperationStatus.CONNECTION_FAILURE;
1459                 break;
1460             default:
1461                 result = StorageOperationStatus.GENERAL_ERROR;
1462                 break;
1463         }
1464         return result;
1465     }
1466
1467     public ResponseFormat getResponseFormat(ComponentException exception) {
1468         return exception instanceof ByResponseFormatComponentException ? getResponseFormat((ByResponseFormatComponentException) exception)
1469             : getResponseFormat((ByActionStatusComponentException) exception);
1470     }
1471
1472     public ResponseFormat getResponseFormat(ByResponseFormatComponentException exception) {
1473         return exception.getResponseFormat();
1474     }
1475
1476     public ResponseFormat getResponseFormat(ByActionStatusComponentException exception) {
1477         return getResponseFormat(exception.getActionStatus(), exception.getParams());
1478     }
1479
1480     public ActionStatus convertFromStorageResponseForRelationshipType(StorageOperationStatus storageResponse) {
1481         ActionStatus responseEnum;
1482         switch (storageResponse) {
1483             case OK:
1484                 responseEnum = ActionStatus.OK;
1485                 break;
1486             case CONNECTION_FAILURE:
1487             case GRAPH_IS_LOCK:
1488                 responseEnum = ActionStatus.GENERAL_ERROR;
1489                 break;
1490             case BAD_REQUEST:
1491                 responseEnum = ActionStatus.INVALID_CONTENT;
1492                 break;
1493             case ENTITY_ALREADY_EXISTS:
1494                 responseEnum = ActionStatus.RELATIONSHIP_TYPE_ALREADY_EXIST;
1495                 break;
1496             case SCHEMA_VIOLATION:
1497                 responseEnum = ActionStatus.RELATIONSHIP_TYPE_ALREADY_EXIST;
1498                 break;
1499             default:
1500                 responseEnum = ActionStatus.GENERAL_ERROR;
1501                 break;
1502         }
1503         log.debug(CONVERT_STORAGE_RESPONSE_TO_ACTION_RESPONSE, storageResponse, responseEnum);
1504         return responseEnum;
1505     }
1506
1507     public ResponseFormat getResponseFormat(StorageException exception) {
1508         ActionStatus status = convertFromStorageResponse(exception.getStorageOperationStatus());
1509         return getResponseFormat(status, exception.getParams());
1510     }
1511
1512     public List<UiLeftPaletteComponent> convertComponentToUiLeftPaletteComponentObject(List<Component> components) {
1513         List<UiLeftPaletteComponent> uiLeftPaletteComponents = new ArrayList<>();
1514         components.forEach(c -> uiLeftPaletteComponents.add(new UiLeftPaletteComponent(c)));
1515         return uiLeftPaletteComponents;
1516     }
1517
1518     public F<StorageOperationStatus, ResponseFormat> toResponseFormat() {
1519         return sos -> getResponseFormat(convertFromStorageResponse(sos));
1520     }
1521
1522     public Optional<UIConstraint> parseToConstraint(final String componentJson, final User user, final ComponentTypeEnum componentTypeEnum) {
1523         final Either<UIConstraint, ResponseFormat> uiConstraintResponseFormatEither = convertJsonToObjectUsingObjectMapper(componentJson, user,
1524             UIConstraint.class, AuditingActionEnum.CREATE_RESOURCE, componentTypeEnum);
1525         if (uiConstraintResponseFormatEither.isRight()) {
1526             return Optional.empty();
1527         }
1528         return Optional.of(uiConstraintResponseFormatEither.left().value());
1529     }
1530
1531     private Either<List, ResponseFormat> parseToConstraints(final String componentJson, final User user, final ComponentTypeEnum componentTypeEnum) {
1532         return convertJsonToObjectUsingObjectMapper(componentJson, user, List.class, AuditingActionEnum.CREATE_RESOURCE, componentTypeEnum);
1533     }
1534
1535     public List<UIConstraint> validateAndParseConstraint(final ComponentTypeEnum componentTypeEnum, final String constraintData,
1536                                                          final User userModifier) {
1537         final String FAILED_TO_PARSE_CONSTRAINT_DATA = "Failed to Parse Constraint Data {}";
1538         final Either<List, ResponseFormat> convertResponse = parseToConstraints(constraintData, userModifier, componentTypeEnum);
1539         if (convertResponse.isRight()) {
1540             log.error(EcompLoggerErrorCode.DATA_ERROR, FAILED_TO_PARSE_CONSTRAINT_DATA, constraintData, convertResponse.right().value());
1541             return Collections.emptyList();
1542         }
1543         final List<Map<String, String>> uiConstraintsMaps = (List<Map<String, String>>) convertResponse.left().value();
1544         if (uiConstraintsMaps == null) {
1545             log.error(EcompLoggerErrorCode.DATA_ERROR, FAILED_TO_PARSE_CONSTRAINT_DATA, constraintData);
1546             return Collections.emptyList();
1547         }
1548         return uiConstraintsMaps.stream().map(dataMap -> new com.fasterxml.jackson.databind.ObjectMapper().convertValue(dataMap, UIConstraint.class))
1549             .collect(Collectors.toList());
1550     }
1551
1552     public Map<String, DataTypeDefinition> getAllDataTypes(final ApplicationDataTypeCache applicationDataTypeCache, final String model) {
1553         final Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes = applicationDataTypeCache.getAll(model);
1554         if (allDataTypes.isRight()) {
1555             final var operationStatus = allDataTypes.right().value();
1556             if (operationStatus == JanusGraphOperationStatus.NOT_FOUND) {
1557                 BeEcompErrorManager.getInstance().logInternalDataError("FetchDataTypes", "Data types are not loaded", ErrorSeverity.ERROR);
1558                 throw new ByActionStatusComponentException(ActionStatus.DATA_TYPES_NOT_LOADED, model);
1559             } else {
1560                 BeEcompErrorManager.getInstance().logInternalFlowError("FetchDataTypes", "Failed to fetch data types", ErrorSeverity.ERROR);
1561                 throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR);
1562             }
1563         }
1564         return allDataTypes.left().value();
1565     }
1566
1567 }